Calling Web API Using HttpClient

Introduction

HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL. It is a supported async feature of .NET framework. HttpClient is able to process multiple concurrent requests. It is a layer over HttpWebRequest and HttpWebResponse. All methods with HttpClient are asynchronous.

Example

In this example, I have created a console application.



To call Web API methods from the console Application, the first step is to install the required packages, using NuGet Package Manager. The following package needs to be installed in the console Application.

Install-Package Microsoft.AspNet.WebApi.Client



Next step is to create HttpClient object. In the following code snippet, the main function calls private static method "CallWebAPIAsync" and this blocks until CallWebAPIAsync completes the process, using wait function.

  1. static void Main(string[] args)  
  2. {  
  3.     CallWebAPIAsync()  
  4.         .Wait();  
  5. }  
  6. static asyncTaskCallWebAPIAsync()  
  7. {  
  8.     using(var client = newHttpClient())  
  9.     {  
  10.         //Send HTTP requests from here.  
  11.     }  
  12. }  
Afterwards, we have set the base URL for the HTTP request and set the Accept header. In this example, I have set Accept header to "application/json" that tells the Server to send the data into JSON format.
  1. using(var client = newHttpClient())  
  2. {  
  3.     client.BaseAddress = newUri("http://localhost:55587/");  
  4.     client.DefaultRequestHeaders.Accept.Clear();  
  5.     client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));  
  6. }  
HTTP GET Request

Following code is used to send a GET request for department, as shown below:
  1. using(var client = newHttpClient())  
  2. {  
  3.     client.BaseAddress = newUri("http://localhost:55587/");  
  4.     client.DefaultRequestHeaders.Accept.Clear();  
  5.     client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));  
  6.     //GET Method  
  7.     HttpResponseMessage response = awaitclient.GetAsync("api/Department/1");  
  8.     if (response.IsSuccessStatusCode)  
  9.     {  
  10.         Departmentdepartment = awaitresponse.Content.ReadAsAsync < Department > ();  
  11.         Console.WriteLine("Id:{0}\tName:{1}", department.DepartmentId, department.DepartmentName);  
  12.         Console.WriteLine("No of Employee in Department: {0}", department.Employees.Count);  
  13.     }  
  14.     else  
  15.     {  
  16.         Console.WriteLine("Internal server Error");  
  17.     }  
  18. }  
In the code given above, I have used GetAsync method to send HTTP GET request asynchronously. When the execution of this method is finished, it returns HttpResponseMessage,  which contains HTTP response. If the response contains success code as response, it means the response body contains the data in the form of JSON. ReadAsAsync method is used to deserialize the JSON object.

HttpClient does not throw any error when HTTP response contains an error code, but it sets the IsSuccessStatusCode property to false. If we want to treat HTTP error codes as exceptions, we can use HttpResponseMessage.EnsureSuccessStatusCode method.

When we run the code, given above, it throws the exception "Internal Server error".
 


We have to configure the serializer to detect then handle self-referencing loops. The following code needs to be placed in Global.asax.cs in Web API:
  1. GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings  
  2. .PreserveReferencesHandling =Newtonsoft.Json.PreserveReferencesHandling.All;  


HTTP POST request

Following code is used to send a POST request for the department:
  1. var department = newDepartment() { DepartmentName = "Test Department" };  
  2. HttpResponseMessage response = awaitclient.PostAsJsonAsync("api/Department", department);  

  3. if (response.IsSuccessStatusCode)  
  4. {  
  5.    // Get the URI of the created resource.  
  6.    UrireturnUrl = response.Headers.Location;  
  7.    Console.WriteLine(returnUrl);  
  8. }  
In this code, PostAsJsonAsync method serializes the object into JSON format and sends this JSON object in POST request. HttpClient has a built-in method "PostAsXmlAsync" to send XML in POST request. Also, we can use "PostAsync" for any other formatter.



HTTP PUT Request

Following code is used to send a PUT request for the department:
  1. //PUT Method  
  2. var department = newDepartment() { DepartmentId = 9, DepartmentName = "Updated Department" };  
  3. HttpResponseMessage response = awaitclient.PutAsJsonAsync("api/Department", department);  
  4. if (response.IsSuccessStatusCode)  
  5. {  
  6.    Console.WriteLine("Success");  
  7. }  
Same as POST, HttpClient also supports all three methods: PutAsJsonAsync, PutAsXmlAsync and PutAsync.



HTTP DELETE Request

Following code is used to send a DELETE request for the department:
  1. intdepartmentId = 9;  
  2. HttpResponseMessage response = awaitclient.DeleteAsync("api/Department/" + departmentId);  
  3. if (response.IsSuccessStatusCode)  
  4. {  
  5.    Console.WriteLine("Success");  
  6. }  
HttpClient only supports DeleteAsync method because Delete method does not have a request body.



Summary

HttpClient is used to sendan HTTP request, using a URL. HttpClient can be used to make Web API requests from the console Application, Winform Application, Web form Application, Windows store Applicatio,n etc.