Dynamically Updating the Request Header of a HttpClientFactory Generated HttpClient, Part 2

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.

 1public void ConfigureServices(IServiceCollection services)
 3    services.AddMemoryCache();
 4    services.AddSingleton<ITokenGenerator, TokenGenerator>();
 6    services.AddHttpClient("RemoteServer", client =>
 7    {
 8        client.BaseAddress = new Uri("http://localhost:5000/api/");
 9        client.DefaultRequestHeaders.Add("Accept", "application/json");
10    }).ConfigureHttpClient((serviceProvider, client) =>
11    {
12        ITokenGenerator tokenGenerator = serviceProvider.GetService<ITokenGenerator>();
13        client.DefaultRequestHeaders.Add("Token", tokenGenerator.GetToken());
14    });
16    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

That’s it, simpler than the approach in the previous post.

Full source code here.

comments powered by Disqus