(C# ASP.NET Core) Minimal DELETE WebApi for Deleting a Record

An HTTP DELETE request is used for deleting a record. The Server sends a 200 OK response on successful deletion alongwith the item that was deleted. Alternatively, it can send 204 No Content if the deleted item is, or cannot be included in the response. Let us see the implementation in this tutorial!
(Rev. 30-Sep-2022)

Categories | About |     |  

Parveen,

How is a DELETE Web Api Created

A DELETE Web Api can be easily created with the MapDelete extension on the application class. The first parameter of this function contains the route template that includes a parameter for the unique ID of the record to be deleted.

The second argument is a function that receives that id as a parameter. This parameter is provided by EF Core from the matched route.

Video Explanation (see it happen!)

Please watch the following youtube video:

Implementing a DELETE Web Api

Open the project that we are discussing in this chapter. Locate the program.cs file and open it! Scroll to the part that you are seeing here. If you are following our course on ASPNET Core then the project file can be obtained from the attached downloads.

As you can see we have used the MapDelete function as explained previously. DbContext is used to find and delete the record from the database.

// extract of the Program.cs file 
// the completed project is in your downloads 
// delete a record of ID 
app.MapDelete("/doctor/{id}", async (MyApiContext ctx, int id) =>
{

  if (await ctx.Doctors.FindAsync(id) is Doctor doctor)
  {

    ctx.Doctors.Remove(doctor);

    await ctx.SaveChangesAsync();

    return Results.Ok(doctor);

    // OR return Results.NoContent() 
  }

  return Results.NotFound();

});

A 200 OK response is sent on successful deletion. The json for the deleted object is also sent as in the response, as per the requirements of the HTTP Protocol.

Testing the API with Postman

Run the project to open the home page so that the server is started. Take note of the URL, and open the Postman software.

Select the request type as DELETE. Type the URL with the route parameter value of id = 1. There is no data to be sent with the request. So click the Send button.

We verify that we receive 200 OK from the server along with the json of the entity that was removed. This means we have tested the minimal Delete Web Api with success!


This Blog Post/Article "(C# ASP.NET Core) Minimal DELETE WebApi for Deleting a Record" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.