在.Net Web Api中使用FluentValidate进行参数验证

在.Net Web Api中使用FluentValidate进行参数验证

安装FluentValidate

在ASP.NET Web Api中请安装 FluentValidation.WebApi版本

创建一个需要验证的Model

    public class Product 
    {
        public string name { get; set; }
        public string des { get; set; }
        public string place { get; set; }
    }

配置FluentValidation,需要继承AbstractValidator类,并添加对应的验证规则

    public class ProductValidator : AbstractValidator<Product>
    {
        public ProductValidator()
        {
            RuleFor(product => product.name).NotNull().NotEmpty();//name 字段不能为null,也不能为空字符串
        }

    }

在Config中配置 FluentValidation

WebApiConfig配置文件中添加

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        ...

        FluentValidationModelValidatorProvider.Configure(config);
    }
}

验证参数

需要在进入Controller之前进行验证,如果有错误就返回,不再进入Controller,需要使用 ActionFilterAttribute

public class ValidateModelStateFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}
  • 如果要让这个过滤器对所有的Controller都起作用,请在WebApiConfig中注册
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.Filters.Add(new ValidateModelStateFilter());

        // Web API routes
        ...

        FluentValidationModelValidatorProvider.Configure(config);
    }
}
  • 如果指对某一个Controller起作用,可以在Controller注册
[ValidateModelStateFilter]
public class ProductController : ApiController
{
    //具体的逻辑
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,993评论 6 342
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,616评论 1 92
  • Just do it!
    dcb81e24a297阅读 230评论 0 0
  • 蓦然回首时,在时光的年轮里,于万万人中邂逅了一座城,却沉溺在了文字里。喜欢,邂逅一轮明月,独守一窗宁静,轻捻一页诗...
    铁杆同学阅读 121评论 0 4