Removing unnecessary request fields from posting a question

Our QuestionPostRequest model is used both in the data repository to pass the data to the stored procedure as well as in the API controller to capture the information in the request body. This single model can't properly cater to both these cases, so we are going to create and use separate models:

  1. In the models folder, create a new model called QuestionPostFullRequest as follows:
public class QuestionPostFullRequest
{
public string Title { get; set; }
public string Content { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public DateTime Created { get; set; }
}

This contains all the properties that are needed by the data repository to save a question.

  1. We can then remove the UserId, UserName, and Created properties from the QuestionPostRequest class:
public class QuestionPostRequest
{
[Required]
[StringLength(100)]
public string Title { get; set; }

[Required(ErrorMessage =
"Please include some content for the question")]
public string Content { get; set; }

}
  1. In the data repository interface, change the PostQuestion method to use the QuestionPostFullRequest model: 
QuestionGetSingleResponse 
PostQuestion(QuestionPostFullRequest question);
  1. In the data repository, change the PostQuestion method to use the QuestionPostFullRequest model: 
public QuestionGetSingleResponse 
PostQuestion(QuestionPostFullRequest question)
{
...
}
  1. We now need to map the QuestionPostRequest received in the API controller to the QuestionFullPostRequest that our data repository expects:
[HttpPost]
public ActionResult<QuestionGetSingleResponse>
PostQuestion(QuestionPostRequest questionPostRequest)
{
var savedQuestion =
_dataRepository.PostQuestion(new QuestionPostFullRequest

{
Title = questionPostRequest.Title,
Content = questionPostRequest.Content,
UserId = "1",
UserName = "[email protected]",
Created = DateTime.UtcNow
});
return CreatedAtAction(nameof(GetQuestion),
new { questionId = savedQuestion.QuestionId },
savedQuestion);
}

We've hardcoded the UserId and UserName for now. In Chapter 11, Securing the Backend, we'll get them from our identity provider.

We've also set the Created property to the current date and time.

  1. Let's run our app and give it a try:

The user and created date are set and returned in the response as expected.

  1. Let's stop the running app.

That completes the separation of the models for the HTTP request and data repository for adding questions. This means we are only requesting the information that is necessary for POST requests to api/questions.

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

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