From 47055beee11aa4121123079f94e8de0952705e5d Mon Sep 17 00:00:00 2001 From: synercoder Date: Fri, 21 Jul 2017 18:17:15 +0200 Subject: [PATCH] Changed usage of HttpClient HttpClient should only have 1 reusable object that exists for the lifetime of the application. See remarks of https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx#Remarks Also more information about this issue can be found here: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ --- .../Internal/UrlChecker.cs | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.Extensions.HealthChecks/Internal/UrlChecker.cs b/src/Microsoft.Extensions.HealthChecks/Internal/UrlChecker.cs index 56800d3..d065a5b 100644 --- a/src/Microsoft.Extensions.HealthChecks/Internal/UrlChecker.cs +++ b/src/Microsoft.Extensions.HealthChecks/Internal/UrlChecker.cs @@ -11,6 +11,7 @@ namespace Microsoft.Extensions.HealthChecks.Internal { public class UrlChecker { + private readonly HttpClient _client; private readonly Func> _checkFunc; private readonly string _url; @@ -21,24 +22,24 @@ public UrlChecker(Func> check _checkFunc = checkFunc; _url = url; + _client = CreateHttpClient(); } public CheckStatus PartiallyHealthyStatus { get; set; } = CheckStatus.Warning; + + protected virtual HttpClient GetHttpClient() => new HttpClient(); public async Task CheckAsync() { - using (var httpClient = CreateHttpClient()) + try { - try - { - var response = await httpClient.GetAsync(_url).ConfigureAwait(false); - return await _checkFunc(response); - } - catch (Exception ex) - { - var data = new Dictionary { { "url", _url } }; - return HealthCheckResult.Unhealthy($"Exception during check: {ex.GetType().FullName}", data); - } + var response = await _client.GetAsync(_url).ConfigureAwait(false); + return await _checkFunc(response); + } + catch (Exception ex) + { + var data = new Dictionary { { "url", _url } }; + return HealthCheckResult.Unhealthy($"Exception during check: {ex.GetType().FullName}", data); } } @@ -61,8 +62,5 @@ public static async ValueTask DefaultUrlCheck(HttpResponseMe }; return HealthCheckResult.FromStatus(status, $"status code {response.StatusCode} ({(int)response.StatusCode})", data); } - - protected virtual HttpClient GetHttpClient() - => new HttpClient(); } }