Invoke Asp.Net Web API with Basic Authentication in C#

Today, we discuss how to call Asp.Net Web API (Rest API), which requires the username and password in the request header in C#. Here we are using API from previous articles (find API source code at https://github.com/techinfocorner/CompanyRestAPI).

Here we are calling our Rest API using Console Application in C#.

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

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

            ////Invoke POST method
            //string response = InvokePost();
            //Console.WriteLine("New Employee Id: " + response);
            //Console.ReadLine();

            ////Invoke PUT method
            //string response = InvokePut();
            //Console.WriteLine(response);
            //Console.ReadLine();

            //Invoke DELETE method
            //string response = InvokeDelete();
            //Console.WriteLine(response);
            //Console.ReadLine();
        }

        static string InvokeGet()
        {
            Uri uri = new Uri("https://localhost:44358/api/employees/getemployees");
            //Uri uri = new Uri("https://localhost:44358/api/employees/getemployee?id=1&name=John");

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

        static string GetResource(Uri uri)
        {
            var response = string.Empty;
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", "basic YWRtaW46YWRtaW4=");
                HttpResponseMessage result = client.GetAsync(uri).Result;

                if (result.IsSuccessStatusCode)
                {
                    response = result.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    response = Convert.ToInt32(result.StatusCode).ToString() + ":" + result.ReasonPhrase;
                }
            }
            return response;
        }     
    }
}

As shown above, in the GetResource() method, we are adding the Authorization to the HttpClient header. Authorization value will be in the Base64 format; for more information on it, visit Basic Authentication in Asp.Net Web API (Rest API).

If you run the application, it displays all employee's details in JSON format, as shown below. If we don’t include Authorization value in the request header, it gives 401:UnAuthorized error.

             

Download C# Rest API Client code from GitHub at https://github.com/techinfocorner/RestAPIClient.