HttpClient Idle Timeout #59050
-
I have an ASP.NET application running on .NET 5 that makes HTTP client requests to another applications API. This API uses a self signed certificate. This is the only option for HTTPS as the system is not connected to the outside internet. To connect the API and accept the self signed certificate, I was using the IHttpClientFactory service like so: services.AddHttpClient("https").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
}); This seemed to be working fine, but I found that every 2 minutes the request would take 2 seconds longer than normal. This request normally takes ~50ms, so this is a significant performance issue. I did some digging and found that the HttpClientHandler is automatically disposed every 2 minutes by the HttpClientFactory to allow for DNS refreshes. I'm not using DNS here so I disabled that like this: services.AddHttpClient("https").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
}).SetHandlerLifetime(System.Threading.Timeout.InfiniteTimeSpan); This appeared to prevent the 2 second delay every 2 minutes, but only if the request is made continuously. If the system is left idle for 2 minutes (no requests are made) than the 2 second delay occurs again. I'm guessing this is because of some sort of idle timeout that is causing the HttpClientHandler to be disposed? I also tried registering the HttpClient as a Singleton instead of using the HttpClientFactory like below and had the same issue: var messageHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
};
HttpClient client = new HttpClient(messageHandler);
services.AddSingleton<HttpClient>(client); Any ideas on how to keep the connection open indefinitely (or at least longer than 2 minutes)? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You might need to set https://docs.microsoft.com/en-us/dotnet/api/system.net.http.socketshttphandler.pooledconnectionidletimeout?view=net-5.0 and use the |
Beta Was this translation helpful? Give feedback.
You might need to set https://docs.microsoft.com/en-us/dotnet/api/system.net.http.socketshttphandler.pooledconnectionidletimeout?view=net-5.0 and use the
SocketsHttpHandler
directly.