前言
本文主要介紹了關于.Net Web Api用FluentValidate參數驗證的相關內容,下面話不多說了,來一起看看詳細的介紹吧。
方法如下
安裝FluentValidate
在ASP.NET Web Api中請安裝 FluentValidation.WebApi版本
創建一個需要驗證的Model
1
2
3
4
5
6
|
public class Product { public string name { get ; set ; } public string des { get ; set ; } public string place { get ; set ; } } |
配置FluentValidation,需要繼承AbstractValidator類,并添加對應的驗證規則
1
2
3
4
5
6
7
|
public class ProductValidator : AbstractValidator<Product> { public ProductValidator() { RuleFor(product => product.name).NotNull().NotEmpty(); //name 字段不能為null,也不能為空字符串 } } |
在Config中配置 FluentValidation
在 WebApiConfig配置文件中添加
1
2
3
4
5
6
7
8
9
|
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes ... FluentValidationModelValidatorProvider.Configure(config); } } |
驗證參數
需要在進入Controller之前進行驗證,如果有錯誤就返回,不再進入Controller,需要使用 ActionFilterAttribute
1
2
3
4
5
6
7
8
9
10
|
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中注冊
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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注冊
1
2
3
4
5
|
[ValidateModelStateFilter] public class ProductController : ApiController { //具體的邏輯 } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://www.jianshu.com/p/cc466c226d79