(转载)NetCore3 WebApi使用模型验证参数合法性

在接口开发过程中免不了要去验证参数的合法性,模型验证就是帮助我们去验证参数的合法性。我们可以在需要验证的model属性上加上Data Annotations特性后就会自动帮我们在action前去验证输入数据的合法性。

1、定义一个class

1
2
3
4
5
6
7
8
9
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验证

1
2
3
4
if (!ModelState.IsValid)
{
return BadRequest();
}

.NetCore WebApi对于参数验证默认返回样式。

1
2
3
4
5
6
7
8
9
10
{
"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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 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
2
3
4
5
6
7
8
9
10
11
 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
3
4
5
6
7
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 }]

转自博客园