Skip to main content

Disable Automatic Model State Validation in ASP.NET Core 2.1

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.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

8 thoughts to “Disable Automatic Model State Validation in ASP.NET Core 2.1”

  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *