Skip to content

Instantly share code, notes, and snippets.

@rbipin
Last active April 2, 2018 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbipin/8e8759375b0274cebed8410117904c5c to your computer and use it in GitHub Desktop.
Save rbipin/8e8759375b0274cebed8410117904c5c to your computer and use it in GitHub Desktop.
Reusing the same HttpClient object, the right way to call different URI's with same HttpClient object
using System;
using System.Net.Http;
using System.Threading.Tasks;
/// <summary>
/// WebApi connection
/// </summary>
namespace WebApiConnectionNameSpace
{
public class WebApiConnection
{
private static HttpClient WebApiClient = null;
private static readonly object threadlock = new object();
/// <summary>
/// Send the request to the Web Api and get the response back
/// </summary>
/// <param name="uri">uri</param>
/// <param name="request">request message</param>
/// <returns></returns>
private async Task<HttpResponseMessage> SendRequestToWebApi(string uri, HttpRequestMessage request)
{
HttpResponseMessage response = null;
try
{
if (request == null)
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
request.RequestUri = new Uri(uri);
//Thread lock to create the HttpClient
lock (threadlock)
{
if (WebApiClient == null)
{
WebApiClient = new HttpClient();
}
}
response = await WebApiClient.SendAsync(request);
return response;
}
catch (Exception ex)
{
throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment