.NetCore3 WebApi使用模型驗證參數合法性


在接口開發過程中免不了要去驗證參數的合法性,模型驗證就是幫助我們去驗證參數的合法性。我們可以在需要驗證的model屬性上加上Data Annotations特性后就會自動幫我們在action前去驗證輸入數據的合法性。

1、定義一個class

1     public class TokenRequest
2     {
3         [Required]
4         [StringLength(6)]
5         public string Username { get; set; }
6 
7         [Required]
8         public string Password { get; set; }
9     }

2、在Controller接口中,使用ModelState.IsValid驗證

      if (!ModelState.IsValid)
      {
            return BadRequest();
      }

.NetCore WebApi對於參數驗證默認返回樣式。

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "|2cf913f6-46e1cc8505a94470.", "errors": { "Password": ["The Password field is required."], "Username": ["The Username field is required."] } }


3、如果想統一驗證,而不是到處都是ModelState.IsValid

(1)定義Attribute繼承ActionFilterAttribute,重寫OnActionExecuting方法

 1     public class ValidateModelAttribute : ActionFilterAttribute
 2     {
 3         public override void OnActionExecuting(ActionExecutingContext context)
 4         {
 5             var modelState = context.ModelState;
 6             if (!modelState.IsValid)
 7             {
 8                 var validationErrors = modelState.Keys
 9                     .SelectMany(key => modelState[key].Errors.Select(x => new ValidationError(key, x.ErrorMessage)));
10                 context.Result = new ObjectResult(validationErrors);
11             }
12         }
13     }
14 
15     public class ValidationError
16     {
17         public string Field { get; set; }
18 
19         public string Message { get; set; }
20 
21         public ValidationError(string field, string message)
22         {
23             Field = field;
24             Message = message;
25         }
26     }

(2)Starup類ConfigureServices

 1             services.AddControllers(options =>
 2             {
 3                 // 添加自定義驗證方式
 4                 options.Filters.Add<ValidateModelAttribute>();
 5             });
 6 
 7             services.Configure<ApiBehaviorOptions>(options =>
 8             {
 9                 // 關閉默認的驗證方式
10                 options.SuppressModelStateInvalidFilter = true;
11             });

 

這樣就可以全局驗證參數,而不是在Controller的Action中到處都是ModelState

驗證效果

1 [{
2   "field": "Password",
3   "message": "The Password field is required."
4 }, {
5   "field": "Username",
6   "message": "The field Username must be a string with a maximum length of 6."
7 }]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM