Jonathan Wood
Jonathan Wood

Reputation: 67193

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.

Upvotes: 1

Views: 2261

Answers (2)

Onurkan Bakırcı
Onurkan Bakırcı

Reputation: 479

You can use

var credentials = Configuration.GetSection("TrackAndTrace").Get<TrackAndTrace>();

TrackAndTrace model should be like this;

public class TrackAndTrace{
    public string DebugBaseUrl {get;set;}
    public string BaseUrl {get;set;}
    public string Username {get;set;}
    public string Password {get;set;}
    public string CompanyCode {get;set;}
}

And then you have to configure services;

var credentials = Configuration.GetSection("TrackAndTrace").Get<TrackAndTrace>();
services.AddHttpClient<TestApi>()
    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler()
        {
           Credentials = new NetworkCredential(credentials.Username, credentials.Password),
        };
    });

Upvotes: 3

abdusco
abdusco

Reputation: 11081

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),
        };
    });

Upvotes: 3

Related Questions