Creating an action method for posting an answer

The final action method we are going to implement is a method for posting an answer to a question:

  1. This method will handle an HTTP POST to the api/question/answer path:
[HttpPost("answer")]
public ActionResult<AnswerGetResponse>
PostAnswer(AnswerPostRequest answerPostRequest)
{
var questionExists =
_dataRepository.QuestionExists(answerPostRequest.QuestionId);
if (!questionExists)
{
return NotFound();
}
var savedAnswer = _dataRepository.PostAnswer(answerPostRequest);
return savedAnswer;
}

The method checks whether the question exists and returns a 404 HTTP status code if it doesn't. The answer is then passed to the data repository to insert into the database. The saved answer is returned from the data repository, which is returned in the response.

  1. Let's try this out by running the app and using Postman. Set the HTTP method to POST and enter the api/questions/answer path. Add the Content-Type HTTP header set to application/json and a request body containing the answer and then click the Send button to send the request:

The answer will be saved and returned in the response as expected.

  1. Let's try this again, but don't include the answer content:

An error occurs in the data repository when the request is sent:

This is because the stored procedures expect the content parameter to be passed into it and protest if it is not.

  1. Let's stop the app so that we're ready to resolve this issue in the next section.

An answer without any content is an invalid answer. Ideally, we should stop invalid requests being passed to the data repository and return HTTP status code 400 to the client with details about what is wrong with the request. How do we do this in ASP.NET Core? Let's find out in the next section.

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

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