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

所属分类: 网络编程 / ASP.NET 阅读数: 1919
收藏 0 赞 0 分享

前言

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

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

更多精彩内容其他人还在看

Asp.net中的mail的发送

Asp.net中的mail的发送
收藏 0 赞 0 分享

用ASP.Net实现文件的在线压缩和解压缩

用ASP.Net实现文件的在线压缩和解压缩
收藏 0 赞 0 分享

ASP.NET中文件上传下载方法集合

ASP.NET中文件上传下载方法集合
收藏 0 赞 0 分享

ASP.NET通过Remoting service上传文件

ASP.NET通过Remoting service上传文件
收藏 0 赞 0 分享

ASP.NET2.0服务器控件之Render方法

ASP.NET2.0服务器控件之Render方法
收藏 0 赞 0 分享

ASP.NET2.0 WebRource,开发微调按钮控件

ASP.NET2.0 WebRource,开发微调按钮控件
收藏 0 赞 0 分享

ASP.NET2.0新特性概述

ASP.NET2.0新特性概述
收藏 0 赞 0 分享

介绍几个ASP.NET中容易忽略但却很重要的方法函数

介绍几个ASP.NET中容易忽略但却很重要的方法函数
收藏 0 赞 0 分享

asp.net2.0如何加密数据库联接字符串

asp.net2.0如何加密数据库联接字符串
收藏 0 赞 0 分享

用.NET 2.0压缩/解压功能处理大型数据

用.NET 2.0压缩/解压功能处理大型数据
收藏 0 赞 0 分享
查看更多