There's a really cool IHttpClientFactory
feature in the new ASP.NET Core 2.1
https://www.hanselman.com/blog/HttpClientFactoryForTypedHttpClientInstancesInASPNETCore21.aspx
I'm trying to use this feature in my ASP.NET Core 2.1 Preview-2 app but I need to use the HttpClient
in my class libraries which are in .NET Standard 2.0
Once I perform AddHttpClient
in ConfigureServices()
in Startup.cs
, how do I pass this HttpClientFactory
or a specific named HttpClient
to an API client I created in my .NET Standard 2.0 class library? This client pretty much handles all the API calls I make to a third party.
Basically, I'm just trying to get the specific named HttpClient
into my thirdPartyApiClient
.
Here's my code in ConfigureServices()
:
public void ConfigureServices(IServiceCollection services)
{
// Create HttpClient's
services.AddHttpClient("Api123Client", client =>
{
client.BaseAddress = new Uri("https://api123.com/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
services.AddHttpClient("Api4567Client", client =>
{
client.BaseAddress = new Uri("https://api4567.com/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
}
AddHttpClient
already handles the registration of the service for you in this scenario. You may get an error if you do it in the above approach. Refer: github.com/dotnet/extensions/issues/1079 – Pappano