1

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.

2 Answers 2

4

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), }; }); 
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.