Search⌘ K

HTTP DELETE

Explore how to implement an HTTP DELETE method in ASP.NET Core JSON Web APIs. Learn to create a DeleteUser action that locates and deletes a user record by ID, handles errors, and returns confirmation to the front-end. This lesson helps you understand API routing, database operations, and testing DELETE requests.

DELETE

To implement HTTP DELETE, you will create an action method and call it DeleteUser(). It will take an id of type integer as an input parameter. You will locate and delete the record with id equal to the one passed as an argument.

Code snippet

C#
// DELETE: api/Users/5
[HttpDelete("{id}")]
public async Task<ActionResult<User>> DeleteUser(int id)
{
var user = await _context.Users.FindAsync(id);
if (user == null)
{
return NotFound();
}
_context.Users.Remove(user);
await _context.SaveChangesAsync();
return user;
}

Explanation

The method is annotated with [HttpDelete("{id}")]. This attribute tells the framework that this method is an HTTP DELETE ...