We can read here YOU\'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE that we should not create and dispose HttpClient for each http request. Instead, it should
Things have changed in a good way in the ASP.NET Core 2.2
release.
The way the HttpClient
is expected to be consumed is through DI only, which internally handles all the necessary caching for you using HttpClientFactory
. The following documentation article has been updated to reflect on these new use cases: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2
Also, @RyanNowak from ASP.NET Core team has covered all these changes in the following ASP.Net Core Community Standup session: https://www.youtube.com/watch?v=Lb12ZtlyMPg If you haven't watched it, I strongly recommend watching it, as it's super informative and educating.
Here is a small sample to showcase the usage. In the Startup.ConfigureServices
method call:
services.AddHttpClient();
Note: There are multiple usage patterns, this is the most basic one. Look into the docs for other patterns, which may suite your needs better.
Later, in the class, where from you'd like to make http requests, take a dependency on IHttpClientFactory
and let DI instantiate it for you as necessary. Here is the sample from Microsoft Docs:
public class BasicUsageModel : PageModel
{
private readonly IHttpClientFactory _clientFactory;
public IEnumerable Branches { get; private set; }
public bool GetBranchesError { get; private set; }
public BasicUsageModel(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task OnGet()
{
var request = new HttpRequestMessage(HttpMethod.Get,
"https://api.github.com/repos/aspnet/docs/branches");
request.Headers.Add("Accept", "application/vnd.github.v3+json");
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
Branches = await response.Content
.ReadAsAsync>();
}
else
{
GetBranchesError = true;
Branches = Array.Empty();
}
}
}