1覆盖自动模型验证

1覆盖自动模型验证

本文介绍了.NET Core 2.1覆盖自动模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在最新的.NET Core 2.1中,引入了用于模型状态验证的自动验证()。

In the latest .NET Core 2.1, an automatic validation for the model state validation is introduced (https://blogs.msdn.microsoft.com/webdev/2018/02/02/asp-net-core-2-1-roadmap/#mvc).

以前,我可以通过以下代码覆盖验证错误响应:

Previously I could override the validation error response by the following code below:

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

    base.OnActionExecuting(context);
}

但是现在它不再起作用了。无需输入重写方法即可响应验证错误。

But now it no longer works. The validation errors is responded without entering the override method.

任何人都有线索吗?
谢谢。

Anyone has any clue?Thanks.

推荐答案

如果您想继续使用 ApiController 属性(它具有其他功能,例如禁用常规路由并允许模型绑定而无需添加 [FromBody] 参数属性),您可以通过您的 Startup.cs 文件:

If you'd like to keep using the ApiController attribute (which has other functions like disabling conventional routing and allowing model binding without adding [FromBody] parameter attributes), you might be able to do it via this in your Startup.cs file:

services.Configure<ApiBehaviorOptions>(opt =>
{
    opt.SuppressModelStateInvalidFilter = true;
});

这样可以使ModelState无效时,不会自动返回400错误。

That will make it so that if the ModelState is invalid it won't automatically return a 400 error.

这篇关于.NET Core 2.1覆盖自动模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:09