Invoke Rest Asp.Net Web API Get Method in C#

In previous articles, we created the simple Asp.Net Rest Web API service, which provides the employee's data. Today we will discuss how to invoke the Asp.Net Web API Get method in C#.

C# provides HttpClient class to invoke the Asp.Net Web API. Open Microsoft Visual Studio 2019 => Create Console Application, name it as RestAPIClient. Add the below code in the Main method of the Program class.

using System;
using System.Net.Http;

namespace RestAPIClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri uri = new Uri("https://localhost:44358/api/employees/getemployees");

            var response = GetResource(uri);

            Console.WriteLine(response);
            Console.ReadLine();
        }

        static string GetResource(Uri uri)
        {
            var response = string.Empty;
            using (var client = new HttpClient())
            {
                HttpResponseMessage result = client.GetAsync(uri).Result;

                if (result.IsSuccessStatusCode)
                {
                    response = result.Content.ReadAsStringAsync().Result;
                }
            }
            return response;
        }
    }
}

As shown above, we have created the object for HttpClient class and returns the response if the result status code is a success. Here we are calling the HttpClient GetSync() method to invoke the Rest API Get() method. Run the application; you can see the output as below.

Here we are not passing any input parameters to API. If you want to pass any input parameters to call Asp.Net Web API Get method, append the input parameters at the end of the URL like https://localhost:44358/api/employees/getemployee?id=1&name=John. Here we are passing two input parameters id & name, and getting the response based on input values provided.

                                                                                            RestAPIClient-31072020.zip (20.75 kb)