• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Tuesday, April 21, 2020

How to Implement DELETE Method in Web API

 Admin     April 21, 2020     .Net, Web API     No comments   

In this article, I am going to discuss how to Implement DELETE Method in Web API Application with an example. Please read our previous article where we discussed how to Implement PUT Method Web API before proceeding to this article as we are going to work with the same example.

How to Implement the DELETE Method in ASP.NET Web API?
The Delete Method in Web API allows us to delete an item. We want to delete a specified employee from the Employees database table. To achieve this Include the following Delete method in EmployeesController.
public class EmployeesController : ApiController
{
    public void Delete(int id)
    {
        using (EmployeeDBContext dbContext = new EmployeeDBContext())
        {
            dbContext.Employees.Remove(dbContext.Employees.FirstOrDefault(e => e.ID == id));
            dbContext.SaveChanges();
        }
    }
}

At this point build the solution, run the application and fire up the Fiddler and issue a Delete request.
  • Set the HTTP verb to DELETE
  • Content-Type: application/json. This tells that we are sending JSON formatted data to the server
  • Finally, click on the execute button as shown below
DELETE Method in WEB API

When we click on the Execute button, it will give us the below response
DELETE Method in WEB API

This works fine and deletes the employee record from the database as expected. The problem here is that since the return type of the Delete method is void, we get status code 204 No Content. When the Deletion is successful, we want to return status code 200 OK indicating that the deletion is successful.

Also when we try to delete an employee whose Id does not exist we get back HTTP status code 500 Internal Server Error. We get status code 500, because of a NULL reference exception. If an item is not found, then we need to return status code 404 Not Found.

How to Fix the above issues?
To fix both of these issues modify the code in the Delete method as shown below.
public class EmployeesController : ApiController
{
    public HttpResponseMessage Delete(int id)
    {
        try
        {
            using (EmployeeDBContext dbContext = new EmployeeDBContext())
            {
                var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);
                if (entity == null)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                        "Employee with Id = " + id.ToString() + " not found to delete");
                }
                else
                {
                    dbContext.Employees.Remove(entity);
                    dbContext.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
            }
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }
}

At this point, issue another DELETE request from the Fiddler. Notice in the response header we have status code 200 OK. Also, when we try to delete an employee whose id does not exist, we get status code 404 Not Found instead of 500 Internal Server Error

Summary:
I Hope this post will be helpful to understand how to implement DELETE Method in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape