Search⌘ K

Creating an Action Method for Deleting a Question

Understand how to implement an ASP.NET Core action method that deletes a question by handling HTTP DELETE requests. Learn to validate question existence, return appropriate HTTP status codes like 404 and 204, and test the endpoint using tools like Postman.

Steps to create an action method to delete 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:

C#
[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 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 that the question 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. ...