C# .NET Core 2.1覆盖自动模型验证

C# .NET Core 2.1覆盖自动模型验证,c#,validation,.net-core-2.1,C#,Validation,.net Core 2.1,在最新的.NET Core 2.1中,引入了模型状态验证的自动验证() 以前,我可以通过以下代码覆盖验证错误响应: public class ApiValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid)

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

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

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

    base.OnActionExecuting(context);
}
但现在它不再起作用了。响应验证错误时不输入覆盖方法

有人有线索吗?
谢谢。

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

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

这样一来,如果ModelState无效,它就不会自动返回400错误。

最近一位朋友问我这个问题,我的方法是用一个自定义的替换默认的
ModalStateInvalidFilter

在我的测试中,我实施了以下建议:

services.AddMvc(options =>
{
    options.Filters.Add(typeof(ValidateModelAttribute));
});


services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });
services.AddMvc(选项=>
{
options.Filters.Add(typeof(ValidateModelAttribute));
});
Configure(options=>{options.SuppressModelStateInvalidFilter=true;});

看起来您只需要删除ApiController属性。这将“还原”逻辑为“旧”样式。@请记住,你是绝对正确的。我真傻,没想到那件事。谢谢你救了我的命,我一直在寻找这段代码很长一段时间了,谢谢你分享这段代码以及博客帖子:)