ASP.NET Core 2.1 introduced the APIController
attribute which performs automatic model state validation and in case of an invalid model state, responds with a 400 bad request error. When the controller is decorated with APIController
attribute, the framework would automatically register a ModelStateInvalidFilter
which runs on the OnActionExecuting
event. This checks for the model state validity and returns the response accordingly. This is a great feature, but sometimes you want to return the custom error instead of the 400 bad request error. In such case, we should disable automatic model state validation.In this post, find out how to disable automatic model state validation in ASP.NET Core 2.1.
Disable Automatic Model State Validation in ASP.NET Core 2.1
You can remove the APIController
attribute to disable the automatic model validation. But, then you will lose the other benefits of this attribute like disabling conventional routing and allowing model binding without adding [FromBody]
parameter attributes.
The better approach to disable the default behavior by setting SuppressModelStateInvalidFilter
option to true
. You can set this option to true
in the ConfigureServices
method. Like,
public void ConfigureServices(IServiceCollection services) { services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; }); }
This will disable the automatic model state validation and now you can return the custom error from the controller action methods.
If you are using ASP.NET Core 2.0 and wants to implement automatic model state validation, then read this post.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.
Helpful, thanks! Unfortunately, too many ads are an annoyance. Either we buy you a coffee or we put up with ads, it’s unreasonable for both.
Agree, I know it’s not a good user experience but not everyone buys me a coffee.
Thank you , It helped me a lot.
Thank you so much
Excellent, worked great! thank you.
excellent. Thanks man.
works for Core 2.2 too, thanks
thanks, I love you