综合开发

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

微信扫一扫,分享到朋友圈

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

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

  • 331

This article is about 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.

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.

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.

Download Now!

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:

...  
        public static async Task<DataTable> GetInfo()  
        {  
            // Initialization.  
            DataTable responseObj = new DataTable();  
  
            // HTTP GET.  
            using (var client = new HttpClient())  
            {  
                // Setting Base address.  
                client.BaseAddress = new Uri("https://localhost:44334/");  
  
                // Setting content type.  
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  
                // Initialization.  
                HttpResponseMessage response = new HttpResponseMessage();  
  
                // HTTP GET  
                response = await client.GetAsync("api/WebApi").ConfigureAwait(false);  
  
                // Verification  
                if (response.IsSuccessStatusCode)  
                {  
                    // Reading Response.  
                    string result = response.Content.ReadAsStringAsync().Result;  
                    responseObj = JsonConvert.DeserializeObject<DataTable>(result);  
                }  
            }  
  
            return responseObj;  
        }  
... 

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 (:grin::yum:) 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:

...  
        public static async Task<DataTable> GetInfo(string requestParams)  
        {  
            // Initialization.  
            DataTable responseObj = new DataTable();  
  
            // HTTP GET.  
            using (var client = new HttpClient())  
           {  
               // Setting Base address.  
               client.BaseAddress = new Uri("https://localhost:44334/");  
  
               // Setting content type.  
                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  
               // Initialization.  
               HttpResponseMessage response = new HttpResponseMessage();  
  
               // HTTP GET  
               response = await client.GetAsync("api/WebApi?" + requestParams).ConfigureAwait(false);  
  
               // Verification  
               if (response.IsSuccessStatusCode)  
               {  
                  // Reading Response.  
                  string result = response.Content.ReadAsStringAsync().Result;  
                  responseObj = JsonConvert.DeserializeObject<DataTable>(result);  
               }  
            }  
            return responseObj;  
        }  
... 

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:

...  
     // Call REST Web API without parameters.  
     DataTable responseObj = Program.GetInfo(requestObj).Result;  
...  
     // Initilization.  
     List<KeyValuePair<string, string>> allIputParams = new List<KeyValuePair<string, string>>();  
     string requestParams = string.Empty;  
  
     // Converting Request Params to Key Value Pair.  
     allIputParams.Add(new KeyValuePair<string, string>("salesChannel", "Online"));  
     allIputParams.Add(new KeyValuePair<string, string>("priority", "M"));  
  
     // URL Request Query parameters.  
     requestParams = new FormUrlEncodedContent(allIputParams).ReadAsStringAsync().Result;  
  
     // Call REST Web API with parameters.  
     responseObj = Program.GetInfo(requestParams).Result;  
... 

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:

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.

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.

Next Recommended Article

微信扫一扫,分享到朋友圈

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

Why can not Tomcat find my web application&quest;

上一篇

Quansight Labs Blog: Creating the ultimate terminal experience in Spyder 4 with Spyder-Terminal

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

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

长按储存图像,分享给朋友