Last active
April 2, 2018 21:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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