Web API Delete Method Example Asp.net C#

Let your API consumer to delete item from database, here we learn how to develop Asp.net Web API Delete Method using C#.

Important: Delete is very risky method in any software, so before you allow user to delete any data from your database, you need to be very careful, you must check if user is verified, also check what type of data user can delete.

Remember to check the authorization before processing the delete request, so you must check if the request has come from authenticated user

Get the tbClient object where clientId match id,if matching client found then delete

Asp.net Web API Delete method using C#

Create an API controller if you don’t have, we develop all functionalities inside the controller below, if you already have existing controller then just copy the following methods and change parameter or variable name as you need.

[ApiController]
[Route("[controller]")]
public class StudentController : ControllerBase
{

}

Following is the example of simple delete method, which will allow API consumer to delete one entity based one Id.

public HttpResponseMessage Delete(int id)            
{
    try
    {
        Client c = null;            
        // Get the tbClient object where clientId match id
        // if matching client found then delete
        // else send a message back saying "no client found"
            
        var returnMessage = Request.CreateResponse(HttpStatusCode.Accepted, c);
        returnMessage.Headers.Location = new Uri(Request.RequestUri + "/" + c.ClientId.ToString());
        return returnMessage;
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

Always keep the delete method type as HttpResponseMessage, so you can send customized response message back to user, so they know the end result of their call

Web API Async Delete Method

The same above method can be asynchronous, in below example I will write the async delete method in Asp.net Core Web API with error handling, where HttpResponseMessage also will be created little differently.

[HttpDelete]
public async Task<HttpResponseMessage> Delete(int id)
{
    HttpResponseMessage returnMessage = new HttpResponseMessage();
    try
    {
        // delete student from database 
        string message = ($"Student Deleted - {id}");
        returnMessage = new HttpResponseMessage(HttpStatusCode.Created);
        returnMessage.RequestMessage = new HttpRequestMessage(HttpMethod.Post, message);
    }
    catch (Exception ex)
    {
        returnMessage = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
        returnMessage.RequestMessage = new HttpRequestMessage(HttpMethod.Post, ex.ToString());
    }
    return await Task.FromResult(returnMessage);
}

In new Web API framework, we do not need to depend on default delete method definition, now we can create any number of delete methods, in typical business situation we always need that, just think of student management API.

Suppose, we want to develop functionalities like DeleteContacts, DeleteGroups, DeleteAlbums ect.

Here are some example how you can define async delete methods in web api.

[Route("DeleteContacts")]
[HttpPost]
public async Task<HttpResponseMessage> DeleteContacts(int id)
{
	HttpResponseMessage returnMessage = new HttpResponseMessage();
	return await Task.FromResult(returnMessage);
}

[Route("DeleteGroups")]
[HttpPost]
public async Task<HttpResponseMessage> DeleteGroups(int id)
{
	HttpResponseMessage returnMessage = new HttpResponseMessage();
	return await Task.FromResult(returnMessage);
}


[Route("DeleteAlbums")]
[HttpPost]
public async Task<HttpResponseMessage> DeleteAlbums(int id)
{
	HttpResponseMessage returnMessage = new HttpResponseMessage();
	return await Task.FromResult(returnMessage);
}

Notice, above methods are just like normal post method, every method has HttpPost attribute, we just need to use route attribute and specify the method name like Route("DeleteAlbums") .

 
Asp.Net Web API Delete Example
Learn Web API: creating API using C# .Net, post, update, delete, read using .net API, set security, check authentication, testing.

C# web service interview questions

Learn API development
Asp.Net C# Web API Examples | Join Asp.Net MVC Course