Creating an action method for deleting a question

Let's implement deleting a question. This follows a similar pattern to the previous methods:

  1. We'll add the action method in a single step as it's similar to what we've done before:
[HttpDelete("{questionId}")]
public ActionResult DeleteQuestion(int questionId)
{
var question = _dataRepository.GetQuestion(questionId);
if (question == null)
{
return NotFound();
}
_dataRepository.DeleteQuestion(questionId);
return NoContent();
}

We use the HttpDelete attribute to tell ASP.NET Core that this method handles HTTP DELETE requests. The method expects the question ID to be included at the end of the path.

The method checks the question that exists before deleting it and returns an HTTP 404 status code if it doesn't exist.

The method returns HTTP status code 204 if the deletion is successful.

  1. Let's try this out by running the app and using Postman. Set the HTTP method to DELETE and enter the path to a question resource. Add the Content-Type HTTP header set to application/json and click the Send button to send the request:

A response with HTTP status code 204 is returned as expected.

  1. Stop our app running so that we are ready to implement our final action method.

That completes the implementation of the action method that will handle DELETE 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
18.116.21.229