Home > Mobile >  Configuring HttpClient/HttpMessageHandler from config file
Configuring HttpClient/HttpMessageHandler from config file

Time:11-22

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.

CodePudding user response:

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

CodePudding user response:

You can use

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 configure services;

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