Header Ads

C#.NET: Access Authorized REST Web API Method

REST Web APIs are used for exchanging data between client and server machines in order to protect data from misusing. Another important aspect of REST web APIs are authorization that adds more security layer for data exchange between client and server machines.

Today, I shall be demonstrating consumption of Authorized REST Web API methods using C#.NET Console Application.


Following are some prerequisites before you proceed any further in this tutorial:
  1. Understanding of JSON Object Mapper.
  2. Knowledge of REST Web API.
  3. Knowledge of ASP.NET MVC5.
  4. Knowledge of C# Programming.
The example code is being developed in Microsoft Visual Studio 2019 Professional. The sample sales data is taken randomly from the internet. I have used ASP.NET MVC - REST Web API Basic Authorization using Nuget Library solution as server side.

Download Now!

Let's begin now.

1) Create new C#.NET Console Application project and name it "AccessAuthorizeRESTWebApi".  
2) Create target JSON object mappers for request/response objects as according to ASP.NET MVC - REST Web API Basic Authorization using Nuget Library server side solution if required.
3) Install "Newtonsoft.Json" & "Microsoft.AspNet.WebApi.Client" NuGet libraries.
4) Create "GetInfo" method without parameters in "Program.cs" file and replace following code in it i.e.

        public static async Task<string> GetInfo()
            // Initialization.
            string responseObj = string.Empty;

            // Posting.
            using (var client = new HttpClient())
                // Initialization
                string userPassword = "AuthnticatedApiUser:PasswordForApi";
                string authorization = Convert.ToBase64String(Encoding.UTF8.GetBytes(userPassword));

                // Setting Authorization.
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorization);

                // Setting Base address.
                // Setting Header key.
                    client.DefaultRequestHeaders.Add("X-ApiKey", "MyRandomApiKeyValue");
                // Process HTTP GET/POST REST Web API
                // Reading Response.
                string result = response.Content.ReadAsStringAsync().Result;
                responseObj = result;

            return responseObj;

In the above code, I am using "HttpClient" library to consume/access Auhtorized REST Web API method. First I have initialized my username/password contract which is required to access the REST Web API in correspondence to ASP.NET MVC - REST Web API Basic Authorization using Nuget Library server side solution, then after initializing my base URL, I have add the REST Web API security key to the content header. Know that security key depends on your server side contract, it is not neccessary that your server side might have any security key at all. Finally, after successfully receiving data from the server I have set my response object.

5) In "Program.cs" file "Main" method write following line of code to call the GET type REST Web API method with and without request query parameters i.e.

     // Call REST Web API without parameters.
     string responseObj = Program.GetInfo().Result;

In the above lines of code, I am simply calling my Auhtorized REST web API method and mapping the response as string object.
6) If you execute the provided solution, you will be able to see following, but, you will need to execute the ASP.NET MVC - REST Web API Basic Authorization using Nuget Library server side solution first i.e.

If the authorization of the REST Web API is not valid then following will be received in the response i.e.


In this article, you will learn to consume Authorized REST Web API method using C#.NET Console Application. You will also learn to utilize "HttpClient" library to consume REST Web APIs. You will learn to pass contracted username/password in your "HttpClient" library and finally you will learn to add security key into the header of  HTTP request call.

1 comment: