Call Rest API PUT Method in C#

Let’s discuss how to update the Asp.Net Web API (Rest API) resource by calling its PUT method In C#. Here we will consider the example API we created in my previous article, updateemployee PUT method.

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

namespace RestAPIClient
{
    class Program
    {
        static void Main(string[] args)
        {
            //Invoke PUT method
            string response = InvokePut();
            Console.WriteLine(response);
            Console.ReadLine();
        }

        static string InvokePut()
        {
            Uri uri = new Uri("https://localhost:44358/api/employees/updateemployee");

            Employee objEmp = new Employee { Id = 1, Name = "David", Country = "United States" };

            var response = UpdateResource(uri, objEmp);
            return response;
        }

        static string UpdateResource(Uri uri, Employee emp)
        {
            var response = string.Empty;
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                // client.DefaultRequestHeaders.Add("Content-type", "application/json");

                HttpResponseMessage result = client.PutAsJsonAsync(uri, emp).Result;

                if (result.StatusCode == HttpStatusCode.OK)
                {
                    response = result.Content.ReadAsStringAsync().Result;
                }
            }
            return response;
        }
    }

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Country { get; set; }
    }
}

As shown above, we are calling the updateemployee PUT method by using the PutAsJsonAsync method available in System.Net.Http. We are passing the employee object, including employee Id, and Rest API updates the resource based on employee Id. If there are no errors, we get the response as “Success” from API.

                                                                                   RestAPIClient-PUT-0508202001.zip (3.79 mb)

Add comment