Reusing same HttpClient, the right way to call different URI’s with same HttpClient object.

Introduction

HttpClient in System.Net.Http is the class provided to send a HTTP request and receive a HTTP response from a URI. I did some research on the HttpClient and found that the class has a problem or rather a disadvantage, though the class implements dispose. Using the class without careful consideration could prove to be a mistake later. Please read this blog post for more details on how wrong use of HttpClient can destabilize the application. I’m will discuss the problem I had to overcome in my project and how I solved it.

Problem

I have a client application that needs to call a web API to get data, but then I needed to make 2 web API calls one to get the authorization token and other to get the required data, both these calls went to two different URI’s. Creating a new instance of the HttpClient as mentioned in the above link was creating a new open socket to the API in the background for each call as explained in blog above and in reference. I needed to create one client that would call two different API URI’s.

My Solution

I created a method SendRequestToWebApi ( SendRequestToWebApi(string uri, HttpRequestMessage request) ), this method accepts the URI of the API to call and also the HttpRequestMessage object. The following is what happens inside the method.

  • A new instance of the static HttpClient object is create if it is already not created.
  • The uri passed to the SendRequestToWebApi is assigned to the HttpRequestMessage object.
  • Call the HttpClient SendAsync method and pass the request object.

Code Snippet is given below.

I tested this method both functionally and because of the known disadvantage of the HttpClient, I also tested this with TCPView and it created only one socket for any number of API call.

Here is the screenshot of my testing with TCPView and using general HttpClient usage and my method is given below. It created multiple connection using general code and only one instance for all the calls from using my solution.

Using general method.

Multiple connection open

Using my code

About My first Attempt

Initially this method would initializes a static HttpClient object and take the URI from the method parameter and assign it to the BaseAddress of the HttClient object.

httpclientobject.BaseAddress=new Uri(uri);

but changing the base address of the already created instance threw the below exception.
“This instance has already started one or more requests. Properties can only be modified before sending the first request.”

Reference

https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

https://contrivedexample.com/2017/07/01/using-httpclient-as-it-was-intended-because-youre-not/

https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx

Site Footer