Assume a HttpClient
having been set up to look like the following (as per standard called with a factory):
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient("weather", weather =>
{
weather.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5");
weather.Timeout = TimeSpan.FromSeconds(15);
}).SetHandlerLifetime(TimeSpan.FromSeconds(15));
Now when using the HttpClient
to call an API I would like to reference the API key directly from the client rather than instantiating or defining it in the separate controller class. How would I go about doing this? Is it possible and if yes how would I reference it?
2
Answers
Use IOptions pattern:
In appsettings:
In program.cs/startup.cs
In the client:
It’s possible to add APIKey when you’re adding HttpClient to DI, Actually it’s the best way:
By so, all Apis that are calling by HttpClient (weather) will use the APIKey, and no need to worry about it anymore.