首页 > 编程 > .NET > 正文

.Net Web Api中利用FluentValidate进行参数验证的方法

2020-01-17 22:11:26
字体:
来源:转载
供稿:网友

前言

本文主要介绍了关于.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{ //具体的逻辑}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对武林网的支持。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表