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. cURL模拟网页登陆

    <?php /** * Created by PhpStorm. * User: Administrator * Date: 2016/7/13 * Time: 23:15 */ $data=' ...

  2. JAVA IO流结构图

    InputStreamReader和OutputStreamWriter分别继承自java.io包中的Reader和Writer,对他们中的抽象的未实现的方法给出实现.如: public int re ...

  3. 【Android Developers Training】 50. 控制相机

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  4. 巧用五招提升Discuz!X运行速度

    Discuz!X使用的是数据库应用程序,所以,当数据库的大小.帖子的数目.会员的数目,这些因素都会影响到程序的检索速度,尤其是当论坛的影响力大了,这个问题就更为突出了,虽然,康盛对Discuz进行了更 ...

  5. KBEngine WebConsole Guide

    https://github.com/kbengine/kbengine/tree/master/docs

  6. Linux 重启和关机命令

    shutdown -r  05:30   在凌晨五点30分关机     shutdown -r  05:30 &     后台执行     shutdown -c    取消前一个关机命令   ...

  7. [图形学] 计算机图形学 with OpenGL开篇

    <计算机图形学>(第四版)正在学习中,学习目的是为了在Unity中使用shader实现不同的渲染效果. 希望在这里能把学习过程中学到的知识和遇到的问题记录下来. 工作环境是:Xcode 8 ...

  8. spring +springmvc+mybatis组合springmvc.xml文件配置

    <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.spr ...

  9. dashDB - Creating a table with CLOB column type

    In order to create a table with clob column type, the table has to be created with "ORGANIZE BY ...

  10. 谈谈关于PHP的代码安全相关的一些致命知识

    谈谈关于PHP的代码安全相关的一些致命知识 目标 本教程讲解如何防御最常见的安全威胁:SQL 注入.操纵 GET 和 POST 变量.缓冲区溢出攻击.跨站点脚本攻击.浏览器内的数据操纵和远程表单提交. ...