从配置文件配置 HttpClient/HttpMessageHandler
Posted
技术标签:
【中文标题】从配置文件配置 HttpClient/HttpMessageHandler【英文标题】:Configuring HttpClient/HttpMessageHandler from config file 【发布时间】:2021-12-31 13:43:03 【问题描述】:我的 appsettings.json 文件包含以下部分。
"TrackAndTrace":
"DebugBaseUrl": "https://localhost:44360/api",
"BaseUrl": "https://example.com/api",
"Username": "Username",
"Password": "Password",
"CompanyCode": "CODE"
,
然后我将HttpClient
配置如下:
services.AddHttpClient<TestApi>()
.ConfigurePrimaryHttpMessageHandler(() =>
return new HttpClientHandler()
// I want to incorporate this somehow:
// services.Configure<TrackAndTraceSettings>(Configuration.GetSection("TrackAndTrace"))
Credentials = new NetworkCredential(????, ???),
;
);
我的问题是:如何从此处的配置文件中获取用户名和密码,并将其分配给HttpClientHandler.Credentials
?
理想情况下,它可以以一种有效的方式完成,只需要从设置文件中读取一次。
【问题讨论】:
【参考方案1】:你可以使用
var credentials = Configuration.GetSection("TrackAndTrace").Get<TrackAndTrace>();
TrackAndTrace 模型应该是这样的;
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;
然后你必须配置服务;
var credentials = Configuration.GetSection("TrackAndTrace").Get<TrackAndTrace>();
services.AddHttpClient<TestApi>()
.ConfigurePrimaryHttpMessageHandler(() =>
return new HttpClientHandler()
Credentials = new NetworkCredential(credentials.Username, credentials.Password),
;
);
【讨论】:
【参考方案2】:使用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),
;
);
【讨论】:
以上是关于从配置文件配置 HttpClient/HttpMessageHandler的主要内容,如果未能解决你的问题,请参考以下文章
为啥 XCode 将配置文件从自动选择一个切换到 iOS 团队配置文件