With the new HttpClientFactory in ASP.NET Core 2.1, it's quite easy to configure custom HTTP clients with things like base urls, default headers etc.
However, I haven't found a way to centralize configuration that lets me inject headers from the current request context. For example, consider a service called with an Authorization
header, which I wish to pass on to all the underlying services as well. It would be awesome to be able to configure this in the .AddHttpClient()
call on services
in the Startup
class, but I can't figure out how to get at the request context from there.
Any ideas?
Working on this answer lead me to multiple answers. I think the first approach is what you are looking for, the second is a good alternative.
In order to configure multiple clients you can use named clients. These clients are registered as transient. Use DI to get the service that has access to the request context.
For that we need IHttpContextAccessor. In this case you don't have to register it yourself, because Identity already does that for you.
Otherwise add the following line in startup:
Next we can configure the named client "github":
Call the client like this:
Another option is to use Typed clients. Here's a short example. For a full example check the link.
Register IHttpContextAccessor:
Create a typed client. I've added two options to add settings. One through the request context and one through a singleton class:
Register the client:
Please note, the code below is just an example. Since the token can't be persisted in the client, you can use the shared HttpClientSettings instead:
Where HttpClientSettings is:
You can use the client like this: