Implementing Delete Method In ASP.NET Web API

So, let’s flip to Visual Studio. In our code, we will add a method for DELETE like this.


This is our class for delete as the return type is void, and we are passing id to which we are going to delete the details of those employees. Then, we created an instance of our TESTEntities. Then, we have to specify the entity we want to remove. So, the lambda is going to return the employee which we want to delete and it removes it from the employees’ collection. And then, you are saving changes.

Now, run the app and open fiddler. We will monitor the request.

At the moment. we got back seven records:



In fiddler, let's change the HTTP verb to DELETE and also pass the id as 7. Let's execute the request.



After you execute that request, go back to SQL Server and check the records.



As you can see from the above record, the id 7 is deleted. Now, let’s look at the response we have got from fiddler.



Notice that it's showing "204 : No content". That is because the return type is void. When the deletion is successful, we should be ideally returning the status code "200: OK", not the 204 error. This is our first problem. The second problem is - when we try to delete an id which does not exist, we do get an exception in fiddler as - 



If you look at the response, the status code is,



It's "500 Internal Server Error". So, basically, it's saying there is an internal server error.  We do get this status code because of an exception:


This lambda is actually searching for an employee which we don’t have here. So, it returns NULL which is then passed to the remove method and remove method is throwing an exception. If you want to know the exception, click on the JSON tab. You will see the following.



The Exception type is system.argumentNullException. The Value cannot be NULL, which is an exception message. As a result of this exception, we are getting the status code as "500: Internal Server Error".

When we are trying to delete an item which does not exist, we should be returning "404 Not Found " instead of "500 Internal Server Error". So, let’s see how to solve these problems

We will change the return type from void to HttpResponseMessage.



Now, we will write an if condition - If the request is null, it should give a message as employee id does not exist and when it exists, it should delete that request.



So, in our try catch block, we have created a variable called as entity and passed our lambda expression to that variable. And, we have specified our condition respectively. So, our final code for DELETE method is,
  1. public HttpResponseMessage Delete(int id)  
  2.        {  
  3.            using (TESTEntities entities = new TESTEntities())  
  4.            {  
  5.                try  
  6.                {  
  7.                    var entity = entities.employeesDatas.FirstOrDefault(e => e.ID == id);  
  8.                    if (entity == null)  
  9.                    {  
  10.                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id = " + id.ToString() + "not found");  
  11.   
  12.                    }  
  13.                    else  
  14.                    {  
  15.                        entities.employeesDatas.Remove(entity);  
  16.                        entities.SaveChanges();  
  17.                        return Request.CreateResponse(HttpStatusCode.OK);  
  18.   
  19.                    }  
  20.                }  
  21.                catch (Exception Ex)  
  22.                {  
  23.   
  24.                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, Ex);  
  25.                }  
  26.                
  27.            }  
  28.   
  29.        }  
Now, let's run our app and see the changes and issue a request in fiddler.



We are trying to delete an employee id which is 6. We do have an employee id which is 6.



So, let’s execute that request.



When we execute the request,  we have got the status code 200. Okay, that means that we have successfully deleted our entry. Now, let’s check our record in SQL Server.



As you can see, the Entry with an id got deleted successfully and we got the status code "200 OK". Now, let’s try to delete the same id. So kindly, execute the same request. And, what we see - 



We got HTTP status code "404 Not found". That literally means that the entry, which it's looking for, does not exist in database. Let's click on JSON tab and see what message we do get.



As you can see, we got an appropriate message here. So, both our problems are resolved.

Conclusion - So, this was all about how to implement Delete Method in ASP.NET Web API. Hope this article was helpful!!

 

Up Next
    Ebook Download
    View all
    Learn
    View all