Skip to main content

Validate Model State automatically in ASP.NET Core 2.0

A ModelState is a collection of name and value pairs submitted to the server during a POST request. It also contains a collection of error messages for each value. The Modelstate represents validation errors in submitted HTML form values. Model validation is the first statement in each controller action method to check for any error before moving forward. A familiar piece of code.

The IsValid property will be true when the values are attached correctly to the model AND no validation rules are broken in the binding process. However, writing this piece of code in every action method increases efforts, lines of code and repetitiveness. It would be appropriate to make model validation a reusable piece or even better would be to automate this process. This post talks about how to validate model state automatically in ASP.NET Core 2.0.

Validate Model State automatically in ASP.NET Core 2.0

To implement this, create a custom Action Filter which checks for the model state validity. When ModelState.IsValid is false, it returns a BadRequestObjectResult containing the ModelState. Like,

Next, apply this custom filter globally in Startup.cs. Like,

That’s it. Now, no need to write the duplicate code again and again for checking model state validity.

[Update: As pointed out by MIROSLAV POPOVIC in the comments, this feature is now coming to ASP.NET Core 2.1. ASP.NET Core 2.1 introduces a new [ApiController] attribute that will trigger automatic model validation and 400 response. More details here.]

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

9 thoughts on “Validate Model State automatically in ASP.NET Core 2.0

  1. What about FluentValidation.AspNetCore with ASP .NET Core MVC app (bot API) when you need just add errors to ModelState? Let say you are using MediatR for commands/queries and MediatR validators. The idea is to catch validation errors from those validators and add them to ModelState and return models to views from MVC action controllers with errors in ModelState rather than returning some JSON errors to failed response. Any thoughts or pointers? TIA!

  2. as Leszek mentions above, it would nice to see an example with FluentValidation.AspNetCore were you actually only use FluentValidation and disabling mvc default ModelState

Leave a Reply to Talking Dotnet Cancel reply

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