Web API中的模型状态验证 [英] Model State Validation in Web API

查看:171
本文介绍了Web API中的模型状态验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义模型验证器,用于验证并返回自定义验证消息.

I have a custom model validator to validate and return custom validation messages.

public void Validate(Object instance) {
                // Perfom validations and thow exceptions if any
                   throw new ValidationException();
               }

现在,我想使用自定义验证器来验证每个即将到来的请求.
中间件和Fitler具有 httpcontext 对象,我应该阅读请求正文,进行反序列化,然后调用我的自定义验证器执行验证.
我取消了默认的自动http 400响应.

Now, I want to validate each coming request using my custom validator.
Middleware and Fitlers have httpcontext object and I am supposed to read the request body, deserailize and then call my custom validator to perform validations.
I have suppressed the default automatic http 400 response.

在每次向Web API发出请求之前,是否有任何适当的方法来调用自定义验证器?

Is there any proper way to call custom validator before each request to Web API?

推荐答案

应用[ApiController]属性时,ASP.NET Core通过返回400带有ModelState作为响应主体的Bad Request自动处理模型验证错误:

When [ApiController] attribute is applied ,ASP.NET Core automatically handles model validation errors by returning a 400 Bad Request with ModelState as the response body :

要禁用自动400行为,请将SuppressModelStateInvalidFilter属性设置为true:

To disable the automatic 400 behavior, set the SuppressModelStateInvalidFilter property to true :

services.AddControllers()
    .ConfigureApiBehaviorOptions(options => 
    {   
        options.SuppressModelStateInvalidFilter = true;     
    });

然后,您可以创建全局操作过滤器以检查ModelState.IsValid并添加您的自定义模型验证,例如:

Then you can create globally action filter to check the ModelState.IsValid and add your custom model validation ,something like :

public class CustomModelValidate : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext context) {
        if (!context.ModelState.IsValid) {
            context.Result = new BadRequestObjectResult(context.ModelState);
        }
    }
}

并将其全局注册以将过滤器应用于每个请求.

And register it globally to apply the filter to each request .

这篇关于Web API中的模型状态验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆