Adding model validation
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:
- Open
QuestionPostRequest.cs
and add the followingusing
statement underneath the existingusing
statements:using System.ComponentModel.DataAnnotations...