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

.NET Core 2.1 Override Automatic Model Validation

在最新的.NET Core 2.1中,引入了模型状态验证的自动验证(https://blogs.msdn.microsoft.com/webdev/2018/02/02/asp-net-core-2-1-roadmap/#mvc)。

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

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;
});

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

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

在我的测试中,我实施了 here 的建议,然后:

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


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