Adding Model Validation

Learn to add model validation checks on request models.

In this section, we are going to add some validation checks on the request models. ASP. NET will then automatically send HTTP status code 400 (bad request) with details of the problem.

Validation is critical to preventing bad data from getting in the database or unexpected database errors from happening, as we experienced in the previous section. Giving the client detailed information for bad requests also ensures the development experience is good because this will help to correct mistakes.

Adding validation to posting a question

We can add validation to a model by adding validation attributes to properties in the model that specify rules that should be adhered to. Let’s add validation to the request for posting a question:

  1. Open QuestionPostRequest.cs and add the following using statement underneath the existing using statements:

Get hands-on with 1200+ tech skills courses.