Call Asp.Net Web API DELETE Method in C#

Here we discuss how to delete the resource by calling Asp.Net Web API (Rest API) Delete method using C#.

using System;
using System.Net;
using System.Net.Http;

namespace RestAPIClient
{
    class Program
    {
        static void Main(string[] args)
        {
            //Invoke DELETE method
            string response = InvokeDelete();
            Console.WriteLine(response);
            Console.ReadLine();
        }
              
        static string InvokeDelete()
        {
            Uri uri = new Uri("https://localhost:44358/api/employees/deleteemployee?id=5");

            var response = DeleteResource(uri);
            return response;
        }

        static string DeleteResource(Uri uri)
        {
            var response = string.Empty;
            using (var client = new HttpClient())
            {
                HttpResponseMessage result = client.DeleteAsync(uri).Result;
                response = " Status Code: " + result.StatusCode.ToString();
            }
            return response;
        }
    }
}

We are invoking the API deleteemployee method using HttpClient.DeleteAsync() method by passing the employee id. Run the application, and it displays the “NoContent” (204) status code on success.

If you run the application again with the same employee id, it displays the “NotFound” (404) error status code because the employee where id is 5 record already deleted.

                                                                                     RestAPIClient-Delete-06082020.zip (3.79 mb)