Call Rest Asp.Net Web API POST Method in C#

In my previous article “Invoke Asp.Net Web API POST Method using Fiddler”, we discussed how to invoke the Asp.net Web API POST method using the Fiddler tool. In this article, we discuss how to achieve the same thing by using C# code.

Open Microsoft Visual Studio 2019 => Create Console Application and import System.Net.Http & Microsoft.AspNet.WebApi.Client packages through Nuget which are required to call the Rest API POST method. Add the code, as shown below.

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

namespace RestAPIClient
{
    class Program
    {
        static void Main(string[] args)
        {
            //Invoke POST method
            string response = InvokePost();
            Console.WriteLine("New Employee Id: " + response);
            Console.ReadLine();
        }

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

            Employee objEmp = new Employee { Name = "Raj", Country = "United States" };

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

        static string PostResource(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.PostAsJsonAsync(uri, emp).Result;

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

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

We have created the object for the Employee class and passing it to the API through PostAsJsonAsync() method. Here we mentioned the Accept type as “application/json”. Once we get the response, we are checking whether the response status code is Created (201) or not.

Run the API from "Create Resource in Rest Asp.Net Web API", then run the client application. It displays the response (here newly created employee id) in the console window as below.

                                                                                             RestAPIClient-0408202001.zip (3.79 mb)

Add comment