'Configuring HttpClient/HttpMessageHandler from config file

My appsettings.json file contains the following section.

"TrackAndTrace": {
  "DebugBaseUrl": "https://localhost:44360/api",
  "BaseUrl": "https://example.com/api",
  "Username": "Username",
  "Password": "Password",
  "CompanyCode": "CODE"
},

And then I'm configuring HttpClient as follows:

services.AddHttpClient<TestApi>()
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler()
        {
           // I want to incorporate this somehow:
           // services.Configure<TrackAndTraceSettings>(Configuration.GetSection("TrackAndTrace"))
           Credentials = new NetworkCredential(????, ???),
        };
    });

My question is: How can I get the Username and Password from the configuration file here, and assign it to HttpClientHandler.Credentials?

Ideally, it could be done in an efficient way such that it only needs to read from the settings file once.



Solution 1:[1]

Use the overload for ConfigurePrimaryHttpMessageHandler that accepts a callback with IServiceProvider parameter.

// assuming you've set up the configuration in ConfigureServices method:
// services.Configure<TrackAndTraceSettings>(Configuration.GetSection("TrackAndTrace"))

services.AddHttpClient<TestApi>()
    .ConfigurePrimaryHttpMessageHandler((serviceProvider) =>
    {
        var config = serviceProvider.GetRequiredService<IOptions<TrackAndTraceSettings>>().Value;
        return new HttpClientHandler()
        {
           Credentials = new NetworkCredential(config.Username, config.Password),
        };
    });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abdusco