Put and Delete Methods in ASP.Net Web API

In my previous article I explained the HTTP Get and Post methods in the ASP.NET Web API.

This article explains the HTTP Put and Delete methods.

SNO. Action HTTP Method Relative URI
1 Update Exiting Employee PUT /api/Employee?uid=uid
2 Delete Record from list DELETE /api/Employee?uid=uid

Creating Resources HTTP PUT

Note: The method name should start with PUT.

This method takes two parameters, one is UID from the URI of the request and emp is from the request body.

This method calls the Update(Emp) method. This method takes employee as a parameter then finds the employee from the list using the uid of the employee given by the client. Then finds the index of this employee from the list of employees then removes the employee and again adds this employee in the list and returns true or false.

This method updates the employee in the list and creates a response with a successful message and adds in a header of the response and returns the response.

  1. /// <summary>  
  2. /// This Method update existing record.  
  3. /// </summary>  
  4. /// <param name="uid">uid of employee</param>  
  5. /// <param name="emp">employee updated record</param>  
  6. /// <returns>after successful updation return httpresponse message with Message.</returns>  
  7. public HttpResponseMessage PutUpdateEmployee(int uid,Employee emp)  
  8. {  
  9.     emp.Uid = uid;  
  10.     if (!Update(emp))  
  11.     {  
  12.         throw new HttpResponseException(HttpStatusCode.NotFound);  
  13.     }  
  14.     else  
  15.    {  
  16.         var response = new HttpResponseMessage();  
  17.         response.Headers.Add("Message""Succsessfuly Updated!!!");  
  18.         return response;  
  19.    }  
  20. }  
  21. /// <summary>  
  22. /// This method take employee object and find index of employee from list  
  23. /// and Remove record from particular index and add record in list.  
  24. /// </summary>  
  25. /// <param name="emp">epmployee record with updated data. </param>  
  26. /// <returns>return true after updation.</returns>  
  27. private Boolean Update(Employee emp)  
  28. {  
  29.     if (emp == null)  
  30.     {  
  31.         throw new ArgumentNullException("emp");  
  32.     }  
  33.     int index = _emp.FindIndex(p => p.Uid == emp.Uid);  
  34.     if (index == -1)  
  35.    {  
  36.         return false;  
  37.    }  
  38.     _emp.RemoveAt(index);  
  39.     _emp.Add(emp);  
  40.    return true;  

Now In this step I will explain how to consume a HTTP service Web API PUT Method in a console application.

Create a Resource (HTTP PUT)

In this method set the base address of the ASP.NET Web API and sets the accept header to application/json that tells the server to send data in JSON format.

PutAsJsonAsyn: This method serializes the object into JSON format and sends a PUT request to.

Then this method returns a Response object.

  1. private static HttpResponseMessage ClientPutRequest(string RequestURI, Employee emp)  
  2. {  
  3.      HttpClient client = new HttpClient();  
  4.      client.BaseAddress = new Uri("http://localhost:1379/");  
  5.      client.DefaultRequestHeaders.Accept.Clear();  
  6.      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  7.      HttpResponseMessage response = client.PutAsJsonAsync(RequestURI, emp).Result;  
  8.      return response;  

Add this code to the Main function of program.cs.->Update Record of employee.

In this method enter the employee id that you want to update then set the employee name, address and city if you want to update any field of the employee and call the method created above and pass the employee object as a parameter then receive the response from this method then call the EnsureSuccessStatusCode method. This method throws an exception when the response status in not success.

Then check IsSuccessStatusCode true and false and return Httpresponsemessage with a header.

  1. //HTTP PUT  
  2. Console.WriteLine("----------------Update Employee -------------------");  
  3. Console.WriteLine("Enter Employee id which you want to update");  
  4. int id =Convert.ToInt16(Console.ReadLine());  
  5. Console.WriteLine("Enter Employee Name if you want to update name of employee");  
  6. string Emppame = Console.ReadLine();  
  7. Console.WriteLine("Enter Employee Address if you want to update Address of employee");  
  8. string EmpAddress = Console.ReadLine();  
  9. Console.WriteLine("Enter Employee City if you want to update City of employee");  
  10. string EmpCity = Console.ReadLine();  
  11. Employee emp = new Employee() { Name = Emppame, Address = EmpAddress, City = EmpCity };  
  12. HttpResponseMessage responsePutMethod = ClientPutRequest("api/Employee?uid=" + id, emp);  
  13. responsePutMethod.EnsureSuccessStatusCode();  
  14. if (responsePutMethod.IsSuccessStatusCode)  
  15. {  
  16.     IEnumerable<string> headerValues = responsePutMethod.Headers.GetValues("Message");  
  17.     Console.WriteLine(headerValues.FirstOrDefault().ToString());  

Then run your application and see the output.

output

Delete Resources HTTP DELETE

Note: The method name should start with Delete.

This method takes employee id as a parameter then gets the employee from the list using employee id given by the client and removes the employee from the list then sends a successful message with response to the client.

  1. /// <summary>  
  2. /// Delete employee from list.  
  3. /// </summary>  
  4. /// <param name="Uid"></param>  
  5. /// <returns></returns>  
  6.   
  7. public HttpResponseMessage DeleteEmployee(int Uid)  
  8. {  
  9.     Employee emp = this.GetEmployee(Uid);  
  10.     if (emp == null)  
  11.    {  
  12.         throw new HttpResponseException(HttpStatusCode.NotFound);  
  13.    }  
  14.     _emp.Remove(emp);  
  15.     var response = new HttpResponseMessage();  
  16.     response.Headers.Add("DeleteMessage""Succsessfuly Deleted!!!");  
  17.     return response;  

Now In this step I will explain how to consume a HTTP service Web API DELETE Method in a console application.

Delete a Resource (HTTP Delete)

In this method set the base address of the ASP.NET Web API and set the accept header to application/json that tells the server to send data in JSON Format.

DeleteAsync: This method request web API with employeeid.

  1. private static HttpResponseMessage ClientDeleteRequest(string RequestURI)  
  2. {  
  3.     HttpClient client = new HttpClient();  
  4.     client.BaseAddress = new Uri("http://localhost:1379/");  
  5.     client.DefaultRequestHeaders.Accept.Clear();  
  6.     HttpResponseMessage response = client.DeleteAsync(RequestURI).Result;  
  7.     return response;  

Then Press F5 and see the output in the console window.

see output