1. nuget添加FluentValidation.WebApi引用.
2. 模型定义:
[Validator(typeof(CustomerValidator))] public class UserModel { public string UserName { get; set; } public string Password { get; set; } }
3. Validator定义:
public class CustomerValidator : AbstractValidator<UserModel> { public CustomerValidator() { RuleFor(customer => customer.UserName).NotEmpty(); RuleFor(customer => customer.Password).NotEmpty().WithMessage("Please specify a first name"); } }
4. Controller定义:
public class DefaultController : ApiController { // POST: api/Default public bool Post([FromBody]UserModel user) { //var validator = new CustomerValidator(); //var results = validator.Validate(user); return user.UserName == "admin"; } }
5. Validation Action Filter定义:
public class ValidateModelStateFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState); } } }
6. 最后在WebApp启动时注册注册ValidationFilter:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Filters.Add(new ValidateModelStateFilter()); FluentValidationModelValidatorProvider.Configure(config); } }
7. 测试: