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

posted on 2017-06-23 11:10  kingreatwill  阅读(863)  评论(0编辑  收藏  举报