C#.NET - Access GET Type REST Web API Method

Data communication is one of the most vital components when working on client machines, mostly to access/store sensitive data onto cloud servers. Any method type of POST or GET of REST Web API can be used for data communication between client machines and cloud servers based on the business requirement.
 
Today, I shall be demonstrating consumption of GET type REST Web API method without any API authorization with and without request query URL parameters using ASP.NET REST Web API platform.
 
C#.NET - Access GET Type REST Web API Method
 
Prerequisites
 
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 GET Method solution as server side.
 
Let's begin now.
 
Step 1
 
Create new C#.NET Console Application project and name it "AccessGetRESTWebApi".  
 
Step 2
 
Create target JSON object mappers for request/response objects as according to ASP.NET MVC - REST Web API GET Method server side solution.
 
Step 3
 
Install "Newtonsoft.Json" & "Microsoft.AspNet.WebApi.Client" NuGet libraries.
 
Step 4
 
Create "GetInfo" method without parameters in "Program.cs" file and replace the following code in it:
  1. ...  
  2.         public static async Task<DataTable> GetInfo()  
  3.         {  
  4.             // Initialization.  
  5.             DataTable responseObj = new DataTable();  
  6.   
  7.             // HTTP GET.  
  8.             using (var client = new HttpClient())  
  9.             {  
  10.                 // Setting Base address.  
  11.                 client.BaseAddress = new Uri("https://localhost:44334/");  
  12.   
  13.                 // Setting content type.  
  14.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  15.   
  16.                 // Initialization.  
  17.                 HttpResponseMessage response = new HttpResponseMessage();  
  18.   
  19.                 // HTTP GET  
  20.                 response = await client.GetAsync("api/WebApi").ConfigureAwait(false);  
  21.   
  22.                 // Verification  
  23.                 if (response.IsSuccessStatusCode)  
  24.                 {  
  25.                     // Reading Response.  
  26.                     string result = response.Content.ReadAsStringAsync().Result;  
  27.                     responseObj = JsonConvert.DeserializeObject<DataTable>(result);  
  28.                 }  
  29.             }  
  30.   
  31.             return responseObj;  
  32.         }  
  33. ... 
In the above code, I am using "HttpClient" library to consume/access GET type REST Web API method without passing any request parameters in the API URL. First I have initialized my base url from ASP.NET MVC - REST Web API GET Method server side solution, secondly, I have initialized content default header as JSON type, at the third step I have called the GET type REST Web API and finally, after successfully receiving all data from the server because I am not passing any request query parameter, I have deserialized the response into my target object mapper. Notice that I have used "DataTable" structure to map my response data. I could have created a target complex JSON object mapper then deserialized it, but, instead I have used "DataTable". You can use either option, since my response JSON object is complex and I am too much of a lazy person (😁😋) to create a complex JSON mapper for my response, so, I simply used "DataTable" structure.
 
Step 5
 
Now, create "GetInfo" method with request query parameters as a Key Value pair string in "Program.cs" file and replace the following code in it:
  1. ...  
  2.         public static async Task<DataTable> GetInfo(string requestParams)  
  3.         {  
  4.             // Initialization.  
  5.             DataTable responseObj = new DataTable();  
  6.   
  7.             // HTTP GET.  
  8.             using (var client = new HttpClient())  
  9.            {  
  10.                // Setting Base address.  
  11.                client.BaseAddress = new Uri("https://localhost:44334/");  
  12.   
  13.                // Setting content type.  
  14.                  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  15.   
  16.                // Initialization.  
  17.                HttpResponseMessage response = new HttpResponseMessage();  
  18.   
  19.                // HTTP GET  
  20.                response = await client.GetAsync("api/WebApi?" + requestParams).ConfigureAwait(false);  
  21.   
  22.                // Verification  
  23.                if (response.IsSuccessStatusCode)  
  24.                {  
  25.                   // Reading Response.  
  26.                   string result = response.Content.ReadAsStringAsync().Result;  
  27.                   responseObj = JsonConvert.DeserializeObject<DataTable>(result);  
  28.                }  
  29.             }  
  30.             return responseObj;  
  31.         }  
  32. ... 
In the above code, I am again using "HttpClient" library to consume/access GET type REST Web API method and passing request query parameters in the API URL format. First I have initialized my base url from ASP.NET MVC - REST Web API GET Method server side solution, secondly, I have initialized content default header as JSON type, at the third step I have combined my request query parameters with the API URL and called the GET type REST Web API and finally, after successfully receiving a database on my request query data, I then deserialize the response into "DataTable" structure in order to map my response data. Know that I have first converted my request query data into Key Value pair and then converted the entire key value pair into string which I have attached with my GET type REST web API.
 
Step 6
 
In "Program.cs" file "Main" method write the following line of code to call the GET type REST Web API method with and without request query parameters:
  1. ...  
  2.      // Call REST Web API without parameters.  
  3.      DataTable responseObj = Program.GetInfo(requestObj).Result;  
  4. ...  
  5.      // Initilization.  
  6.      List<KeyValuePair<stringstring>> allIputParams = new List<KeyValuePair<stringstring>>();  
  7.      string requestParams = string.Empty;  
  8.   
  9.      // Converting Request Params to Key Value Pair.  
  10.      allIputParams.Add(new KeyValuePair<stringstring>("salesChannel""Online"));  
  11.      allIputParams.Add(new KeyValuePair<stringstring>("priority""M"));  
  12.   
  13.      // URL Request Query parameters.  
  14.      requestParams = new FormUrlEncodedContent(allIputParams).ReadAsStringAsync().Result;  
  15.   
  16.      // Call REST Web API with parameters.  
  17.      responseObj = Program.GetInfo(requestParams).Result;  
  18. ... 
In the above lines of code, I am simply calling my GET type REST web API method without passing any request query parameters and storing my response as "DataTable" structure. Then I first convert my request query parameters into Key Value pair, then, I convert my request query parameters into string and then finally, I call my GET type REST web API method with input request query data and store my response as "DataTable" structure.
 
Step 7
 
If you execute the provided solution, you will be able to see the following, but, you will need to execute the ASP.NET MVC - REST Web API GET Method server side solution first:
 
C#.NET - Access GET Type REST Web API Method
 
If you debug the code and look into flowing piece of code then you will see that request query parameters are properly converted for URL parameter passing using key value pair conversion.
 
C#.NET - Access GET Type REST Web API Method
 

Conclusion

 
In this article, you learned to consume GET type REST Web API method without any API authorization with and without request query URL parameters using ASP.NET REST Web API platform. You also learned to utilize "HttpClient" library to consume REST Web APIs, to convert URL parameters into Key Value pair, to call GET type REST web API with and without request query URL parameters and finally,  about desiralizing REST web API response directly into "DataTable" structure.


Similar Articles