Adding validation to posting an answer

Let's add validation to the request for posting an answer:

  1. Open AnswerPostRequest.cs and add the following using statement:
using System.ComponentModel.DataAnnotations;
  1. Add the following validation attributes and make QuestionId nullable:
public class AnswerPostRequest
{
[Required]
public int? QuestionId { get; set; }
[Required]
public string Content { get; set; }
...
}

So, we require the QuestionId to be supplied along with the answer content.

Notice the ? after the int type on the QuestionId property.

The ? allows the property to have a null value as well as the declared type. T? is shortcut syntax for Nullable<T>.

So, why does QuestionId need to be able to hold a null value? This is because an int type defaults to 0 and so if there is no QuestionId in the request body, AnswerPostRequest will come out of the model binding process with QuestionId set to 0, which will pass the required validation check. This means the Required attribute won't catch a request body with no QuestionId. If the QuestionId type is nullable, then it will come out of the model binding processing with a null value if it's not in the request body and fail the required validation check, which is what we want.

  1. We need to change the PostAnswer method in QuestionsController.cs to now reference the Value property in QuestionId:
[HttpPost("answer")]
public ActionResult<AnswerGetResponse>
PostAnswer(AnswerPostRequest answerPostRequest)
{
var questionExists =
_dataRepository.QuestionExists(answerPostRequest.QuestionId.Value);
if (!questionExists)
{
return NotFound();
}
var savedAnswer =
_dataRepository.PostAnswer(answerPostRequest);
return savedAnswer;

}

So, model validation is super easy to implement in our request models. The following are some more validation attributes that are available in ASP.NET Core:

  • [Range]: Checks that the property value falls within the given range
  • [RegularExpression]: Checks that the data matches the specified regular expression
  • [Compare]: Checks that two properties in a model match
  • [CreditCard]: Checks that the property has a credit card format
  • [EmailAddress]: Checks that the property has an email format
  • [Phone]: Checks that the property has a telephone format
  • [Url]: Checks that the property has a URL format

We haven't added any validation to the UserId, UserName, or Created properties in our request models. In the next section, we are going to find out why and properly handle these properties.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.101.192