Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

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

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.