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