using FluentValidation;
using FluentValidation.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace webapiTest.Controllers
{
public class DefaultController : ApiController
{
// GET: api/Default
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET: api/Default/5
public string Get(int id)
{
return "value";
}

// POST: api/Default
public bool Post([FromBody]UserModel user)
{
//var validator = new CustomerValidator();
//var results = validator.Validate(user);

return user.UserName=="admin";
}

// PUT: api/Default/5
public void Put(int id, [FromBody]string value)
{
}

// DELETE: api/Default/5
public void Delete(int id)
{
}
}

[Validator(typeof(CustomerValidator))]
public class UserModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
public class CustomerValidator : AbstractValidator<UserModel>
{
public CustomerValidator()
{
RuleFor(customer => customer.UserName).NotEmpty();
RuleFor(customer => customer.Password).NotEmpty().WithMessage("Please specify a first name");
}
}

}

注册:

using FluentValidation.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace webapiTest
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务

// Web API 路由
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

//Fluent Validation
config.Filters.Add(new ValidateModelStateFilter());
FluentValidationModelValidatorProvider.Configure(config);
}
}
}

过滤器:

using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace webapiTest
{
public class ValidateModelStateFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
}

结果:

{
"Message": "请求无效。",
"ModelState": {
"user.Password": [
"Please specify a first name"
]
}
}

参考;http://nodogmablog.bryanhogan.net/2016/12/fluent-validation-with-web-api-2/

https://stackoverflow.com/questions/12975291/how-to-hook-fluentvalidator-to-a-web-api/21350606

demo:http://nodogmablog.bryanhogan.net/wp-content/uploads/2016/12/FluentValidationExample.zip

Fluent Validation with Web Api 2的更多相关文章

  1. Model Validation in ASP.NET Web API

    Model Validation in ASP.NET Web API 原文:http://www.asp.net/web-api/overview/formats-and-model-binding ...

  2. Asp.Net Web API 2第十五课——Model Validation(模型验证)

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文参考链接文章地址htt ...

  3. Web API中的模型验证Model Validation

    数据注释 在ASP.NET Web API中,您可以使用System.ComponentModel.DataAnnotations命名空间中的属性为模型上的属性设置验证规则. using System ...

  4. MVC学习系列12---验证系列之Fluent Validation

    前面两篇文章学习到了,服务端验证,和客户端的验证,但大家有没有发现,这两种验证各自都有弊端,服务器端的验证,验证的逻辑和代码的逻辑混合在一起了,如果代码量很大的话,以后维护扩展起来,就不是很方便.而客 ...

  5. 我这么玩Web Api(二):数据验证,全局数据验证与单元测试

    目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试   一.模型状态 - ModelState 我理解 ...

  6. ASP.NET Web API Model-ModelMetadata

    ASP.NET Web API Model-ModelMetadata 前言 前面的几个篇幅主要围绕控制器的执行过程,奈何执行过程中包含的知识点太庞大了,只能一部分一部分的去讲解,在上两篇中我们看到在 ...

  7. Web APi之认证(Authentication)两种实现方式后续【三】(十五)

    前言 之前一直在找工作中,过程也是令人着实的心塞,最后还是稳定了下来,博客也停止更新快一个月了,学如逆水行舟,不进则退,之前学的东西没怎么用,也忘记了一点,不过至少由于是切身研究,本质以及原理上的脉络 ...

  8. 使用ASP.NET WEB API构建基于REST风格的服务实战系列教程(一)——使用EF6构建数据库及模型

    系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 使用Entity Framework Code First模式构建数据库对象 已经决定使用EF C ...

  9. Exception Handling in ASP.NET Web API webapi异常处理

    原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...

随机推荐

  1. zoom与scale的异同

    zoom与scale的异同点 作为一名前端,尤其是页面要兼容ie浏览器的前端,肯定对着两个属性都很熟悉. zoom和scale都是css中常用的放大和缩小一个元素的方法,在scale还没有成为css3 ...

  2. phpstrom识别phalcon框架模板文件的配置

  3. JAVA类型擦除

    Java泛型-类型擦除 一.概述 Java泛型在使用过程有诸多的问题,如不存在List<String>.class, List<Integer>不能赋值给List<Num ...

  4. vue1与vue2的路由 以及vue2项目大概了解

    vue1的路由 1.设置根组件  Vue.extend() 2.设置局部组件  Vue.extend({template:"/home"}) 3.实例化路由   var route ...

  5. 【原】无脑操作:eclipse + maven搭建SSM框架

    网上看到一些Spring + Spring MVC + MyBatis框架的搭建教程,不是很详细或是时间久远了,自己动手整一个简单无脑的! 0.系统环境 1)Windows 10 企业版 2)JDK ...

  6. 2.vue 安装教程

    安装node.js 从node.js官网下载并安装node,安装过程很简单,一路"下一步"就可以了(傻瓜式安装). 安装完成之后,打开命令行工具,输入 node -v,如下图,如果 ...

  7. 1.Smarty的下载安装

    下载地址:https://github.com/smarty-php/smarty/tree/v3.1.29 官网:smarty.net 下载解压后的目录:

  8. Mac之OS系统下搭建JavaEE环境 <一> 之JDK的安装配置

    这篇文章介绍了如何在Mac下搭建我们的JavaEE工作环境,对于初学者来说还是比较通俗易懂的. 一.JDK的安装及配置 1.首先我们到Oracle官网下JDK http://www.oracle.co ...

  9. java IO之 编码 (码表 编码 解码 转换流)

    编码 什么是编码? 计算机中存储的都是二进制,但是要显示的时候,就是我们看到的却可以有中国 ,a  1 等字符 计算机中是没有存储字符的,但是我们却看到了.计算机在存储这些信息的时候,根据一个有规 则 ...

  10. DELPHI XE5安装

    1.安装XE5 2. HNFJ-DPADCW-BDWCFU-FPNN QDF4-CTSDHV-RDFCFE-FEAN HNFK-BCN8NN-78N53D-H4RS 破解补丁使用方法: (1).复制压 ...