在ASP.NET Web Api中請安裝 FluentValidation.WebApi
版本bash
public class Product
{
public string name { get; set; }
public string des { get; set; }
public string place { get; set; }
}
複製代碼
配置FluentValidation
,須要繼承AbstractValidator
類,並添加對應的驗證規則ide
public class ProductValidator : AbstractValidator<Product>
{
public ProductValidator()
{
RuleFor(product => product.name).NotNull().NotEmpty();//name 字段不能爲null,也不能爲空字符串
}
}
複製代碼
在 WebApiConfig
配置文件中添加ui
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
...
FluentValidationModelValidatorProvider.Configure(config);
}
}
複製代碼
須要在進入Controller
以前進行驗證,若是有錯誤就返回,再也不進入Controller
,須要使用 ActionFilterAttribute
spa
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
{
//具體的邏輯
}
複製代碼