HttpDelete Method In ASP.NET Web API - Part Six

In previous articles of the ASP.NET Web API series, I’ve used HttpPut method of HTTP by which we can update a member into our specific database. So for updating information as per our expectations we use HttpPut method by using a URI. In this article of the series, I’ll work on Delete() method of HTTP. You can follow ASP.NET Web API series for the purpose of how Get() and, Post() and Put() method requests work as given in the following links –

Now, we’ll work on another method of HTTP that is Delete() method which is responsible for Deleting existing data to the server. I’m going to working with my previous project Entity Framework that I have created in previous articles of the series in Using Entity Framework In ASP.NET Web API – Part Three.

In this, I will show you how we can delete data which would be saved in my SQL database by using Delete() method. So just flip to Visual Studio and open your previous project.

Under the IEmployeTest Interface create a method for deleting a record of employees followed by the table name, that is Employee.
  1. string DeleteEmploye(int empID);  
Here is the screenshot of IEmployeInterface -
 


In the EmployeTest class the object of Employee, which is our table, returns the existing table record in the database. Call Remove method to remove a record. After that Call SaveChanges() method for changes of the employee information into the database.
  1. public string DeleteEmploye(int empId) {  
  2.     Employe emp = db.Employes.Where(x => x.EmpID == empId).Single < Employe > ();  
  3.     db.Employes.Remove(emp);  
  4.     db.SaveChanges();  
  5.     return "Record has successfully Deleted";  
  6. }  
Follow the screenshot of EmployeTest class.
 


We need to make some changes in the controller as well. I have to implement the DeleteEmploye () method here, using the [HttpDelete] method.
  1. [HttpDelete]  
  2. public string DeleteEmploye(int id) {  
  3.     return empTest.DeleteEmploye(id);  
  4. }  
Follow the screenshot of Employee controller -
 


Now all the code is set, flip to your SQL Server Management. I have two records in the Employee table let’s suppose I want to delete the second row that holds EmpID 2.
 


I’m going to use here Postman for the Delete request. Open Postman and call Delete method, enter your Web API URL make sure your Visual Studio project is in running mode, for this request I need to call DeleteEmploye method in the URL along with ID which would I like to delete. Finally click on the send button for making a request. URL for delete request would be –

http://localhost:1461/api/employe/DeleteEmploye?id=2 


Look at screenshot, I have got a successful message. That means our data has been deleted in the database.
 


So, here I’ve successfully deleted my second record.
 
 
 
Thanks for reading this article, stay tuned with us for more on ASP.NET Web API. 


Similar Articles