Instantly share code, notes, and snippets.

Embed
What would you like to do?
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