Delete Resource in Asp.Net Web API using HTTP DELETE

Today we discuss how to delete the resource in Asp.Net Web API (Rest API) using HTTP DELETE verb. We use the same Company example where we write the code to delete the employee based on the Id, as shown below.

using CompanyRestAPI.Models;
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CompanyRestAPI.Controllers
{
    public class EmployeesController : ApiController
    {
        // DELETE: Delete Employee
        [Route("api/employees/deleteemployee")]
        [HttpDelete]
        public HttpResponseMessage DeleteEmployee(int id)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }

                if (Company.FoundEmployee(id))
                {
                    bool isSuccess = Company.DeleteEmployee(id);
                    return Request.CreateResponse(HttpStatusCode.NoContent);
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
    }
}

First, check whether a particular employee record is there or not. If the employee is not available, return HttpStatusCode.NotFound (404) status code to the client. Otherwise, delete the employee record based on Id and return HttpStatusCode.NoContent (204) status code which is success code for the DELETE method.                                          

                                                                                   CompanyRestAPI-DELETE-06082020.zip (55.61 mb)

Add comment