.NET Core 2.1 Override Automatic Model Validation

大憨熊 提交于 2019-12-22 08:08:42

问题


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.


回答1:


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

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




回答2:


I was recently asked by a friend about this and my approach was to replace the default ModalStateInvalidFilter by a custom one.

In my test I've implemented the suggestion from here and then:

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


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


来源:https://stackoverflow.com/questions/51125569/net-core-2-1-override-automatic-model-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!