Last post Jul 24, 2019 08:11 AM by 1jus
Jul 18, 2019 04:30 PM|1jus|LINK
I have been reading several articles about the best way to use HttpClient. One article suggests a single instance in the Global.asax file. Does anyone have a definitive answer as to whether this is the best way to implement? The example code in the article
public class WebApiApplication : System.Web.HttpApplication
internal static HttpClient httpClientInstance;
protected void Application_Start()
httpClientInstance = new HttpClient();
httpClientInstance.DefaultRequestHeaders.ConnectionClose = false;
("some uri").ConnectionLeaseTimeout = 60 * 1000;
("some other uri").ConnectionLeaseTimeout = 60 * 1000;
("some other other uri").ConnectionLeaseTimeout = 60 * 1000;
Jul 18, 2019 04:57 PM|mgebhard|LINK
The standard .NET documentation covers HttpClient in detail and includes recommended patterns.
This code snippet copied from the docs is perfectly fine.
public class GoodController : ApiController
private static readonly HttpClient HttpClient;
HttpClient = new HttpClient();
Other options are a Singleton pattern with one Singleton for each service consumed.
Dependency inject which is the standard in ASP.NET Core.
Jul 19, 2019 07:50 AM|1jus|LINK
So would you say that the placement in global.asax would make sense for application wide usage? Also, do you have any suggestions regarding stale DNS/DNS caching?
Jul 23, 2019 05:22 AM|Nan Yu|LINK
You can create in Global.asax . A Singleton HttpClient does not respect DNS changes .Re-using an instance of HttpClient means that it holds on to the socket until it is closed so if you have a DNS record update occurring on the server the client will never
know until that socket is closed . One easy workaround is to set the keep-alive header to false so the socket will be closed after each request, this obviously results in sub-optimal performance but if you do not care , or you can set the `ConnectionLeaseTimeout
` which specifies how long (in ms) the TCP socket can stay open :
.ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
You can also need to reduce the DNS cache timeout which we can do by setting the DnsRefreshTimeout on the ServicePointManager class like :
ServicePointManager.DnsRefreshTimeout = (int)1.Minutes().TotalMilliseconds;
Jul 24, 2019 08:11 AM|1jus|LINK
Thanks Nan Yu :)