Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Implementing Delete method in ASP.NET Web API

Suggested Videos
Part 5 - ASP.NET Web API Content Negotiation
Part 6 - ASP.NET Web API MediaTypeFormatter
Part 7 - Implementing post method in ASP.NET Web API



In this video we will discuss implementing DELETE method in ASP.NET Web API. Delete allows us to delete an item.



We want to delete the specified employee from the Employees table. Include the following Delete() method in EmployeesController.

public void Delete(int id)
{
    using (EmployeeDBEntities entities = new EmployeeDBEntities())
    {
        entities.Employees.Remove(entities.Employees.FirstOrDefault(e => e.ID == id));
        entities.SaveChanges();
    }
}

There are 3 problems with the above code
  1. The above code deletes the employee only when the ID of the employee that you want to delete exists.
  2. When the deletion is successful, since the method return type is void we get status code 204 No Content. We should be returning status code 200 OK.
  3. If the ID of the employee that we want to delete does not exist, there is an exception and as a result of it the Web API returns status code 500 internal server error. If an item is not found, we should be returning status code 404 Not Found.
To fix all the above problems, modify the code in Delete() method as shown below

public HttpResponseMessage Delete(int id)
{
    try
    {
        using (EmployeeDBEntities entities = new EmployeeDBEntities())
        {
            var entity = entities.Employees.FirstOrDefault(e => e.ID == id);
            if (entity == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                    "Employee with Id = " + id.ToString() + " not found to delete");
            }
            else
            {
                entities.Employees.Remove(entity);
                entities.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK);
            }
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

ASP.NET Web API tutorial for beginners

6 comments:

  1. I am getting method not allowed error can you please help me to resolve it.

    ReplyDelete
  2. I am getting HTTP/1.1 405 Method Not Allowed in fiddler

    ReplyDelete
  3. Change the type to delete in Fiddler

    ReplyDelete
  4. Hi, Can anyone tell how to response Bad Request in case of passing extra parameter in post API call.

    Example :

    {"Para1":"Value1","Para2":"Value2"} suppose this is required in my API and if I pass {"Para1":"Value1","Para2":"Value2","Para3":"Value3"} still my API working fine.

    I want in above case case API should response as BAD API Call.

    Please answer me ASAP.
    Thanks

    ReplyDelete

It would be great if you can help share these free resources