首页 新闻 会员 周边 捐助

ASP.NET Core: 注册 HttpClient 时如何从 IOptions 中读取配置

0
悬赏园豆:30 [已解决问题] 解决于 2023-02-20 12:46

目前是直接通过 IConfiguration 从 appsettings.json 中读取的

services.AddHttpClient(
    "zzk-api",
    x => x.BaseAddress = new Uri(configuration.GetValue($"{sectionName}:ZzkApiAddress", "http://zzk_api")))
    .SetHandlerLifetime(TimeSpan.FromMinutes(5))
    .AddPolicyHandler(GetRetryPolicy());

想改为从 ZzkManagerOptions 中获取

services.AddHttpClient(
    "zzk-api",
    x => x.BaseAddress = new Uri(options.ZzkApiAddress))
    .SetHandlerLifetime(TimeSpan.FromMinutes(5))
    .AddPolicyHandler(GetRetryPolicy());

请问在 AddHttpClient 时如何获取 IOptions<ZzkManagerOptions>?

dudu的主页 dudu | 高人七级 | 园豆:29642
提问于:2023-02-20 11:52
< >
分享
最佳答案
0

原来 HttpClient 已经考虑了这种情况,提供了现成的扩展方法

public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Action<IServiceProvider, HttpClient> configureClient)
{ }

用这个扩展方法可以轻松实现

services.AddHttpClient("zzk-api", (sp, httpClient) =>
{
    var options = sp.GetRequiredService<IOptions<ZzkManagerOptions>>().Value;
    httpClient.BaseAddress = new Uri(options.ZzkApiAddress);
})
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.AddPolicyHandler(GetRetryPolicy());
dudu | 高人七级 |园豆:29642 | 2023-02-20 12:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册