Full source code here.
This is a alternative to the approach described in a previous post.
On a slack channel there was some discussion around the use of a little known extension method on HttpClientBuilder
, ConfigureHttpClient
. Using this extension method provides another way to dynamically alter the header of a HttpClient
provided by the factory.
In ConfigureServices(..)
I setup the two services I need, the MemoryCache
and the TokenGenerator
.
Then, where I configure the HttpClientFactory
I call the ConfigureHttpClient
, pass it an Action
that takes the ServiceProvider
and the HttpClient
I’m configuring.
Inside the Action
, I take a TokenGenerator
from the service collection and then add the token to the client header.
public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddSingleton<ITokenGenerator, TokenGenerator>(); services.AddHttpClient("RemoteServer", client => { client.BaseAddress = new Uri("http://localhost:5000/api/"); client.DefaultRequestHeaders.Add("Accept", "application/json"); }).ConfigureHttpClient((serviceProvider, client) => { ITokenGenerator tokenGenerator = serviceProvider.GetService<ITokenGenerator>(); client.DefaultRequestHeaders.Add("Token", tokenGenerator.GetToken()); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
That’s it, simpler than the approach in the previous post.
Full source code here.