How to Consume Rest API Using Http Client In C#

 Admin   
39561 View    Jan 17 2020 11:20PM

The .NET 2.0 included WebClient class to communicate with web server using HTTP protocol. However, WebClient class had some limitations. The .NET 4.5 includes HttpClient class to overcome the limitation of WebClient. Here, we will use HttpClient class in console application to send data to and receive data from Web API which is hosted on local IIS web server. You may use HttpClient in other .NET applications also such as MVC Web Application, windows form application, windows service application etc.

Step 1:

First, create a console application in Visual Studio 2013 for Desktop.

Step 2:

Open NuGet Package Manager Console from TOOLS -> NuGet Package Manager -> Package Manager Console and execute following command.

Install-Package Microsoft.AspNet.WebApi.Client

Step 3:

Now, create a Student model class because we will send and receive Student object to our Web API.

Example: Model Class

 

public class Student

{

    public int Id { get; set; }

    public string Name { get; set; }

}

Send GET Request

The following example sends an HTTP GET request to Student Web API and displays the result in the console.

Example: Send HTTP GET Request using HttpClient

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Net.Http;

using System.Net.Http.Headers;

 

namespace HttpClientDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            using (var client = new HttpClient())

            {

                client.BaseAddress = new Uri("http://localhost:60464/api/");

                //HTTP GET

                var responseTask = client.GetAsync("student");

                responseTask.Wait();

 

                var result = responseTask.Result;

                if (result.IsSuccessStatusCode)

                {

 

                    var readTask = result.Content.ReadAsAsync<Student[]>();

                    readTask.Wait();

 

                    var students = readTask.Result;

 

                    foreach (var student in students)

                    {

                        Console.WriteLine(student.Name);

                    }

                }

            }

            Console.ReadLine();

        }       

    }

}

 

 

Send POST Request

Similarly, you can send HTTP POST request using PostAsAsync() method of HttpClient and process the result the same way as GET request.

The following example send http POST request to our Web API. It posts Student object as json and gets the response.

Example: Send HTTP POST Request using HttpClient

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Net.Http;

using System.Net.Http.Headers;

 

namespace HttpClientDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            var student = new Student() { Name = "Steve" };

 

            var postTask = client.PostAsJsonAsync<Student>("student", student);

            postTask.Wait();

 

            var result = postTask.Result;

            if (result.IsSuccessStatusCode)

            {

 

                var readTask = result.Content.ReadAsAsync<Student>();

                readTask.Wait();

 

                var insertedStudent = readTask.Result;

 

                Console.WriteLine("Student {0} inserted with id: {1}", insertedStudent.Name, insertedStudent.Id);

            }

            else

            {

                Console.WriteLine(result.StatusCode);

            }

        }

    }

}