gpt4 book ai didi

c# - HttpClientFactory - 通过名称获取命名的类型化客户端

转载 作者:太空狗 更新时间:2023-10-29 23:19:59 28 4
gpt4 key购买 nike

HttpClientFactory 提供以下扩展方法:

public static IHttpClientBuilder AddHttpClient<TClient>(this IServiceCollection services, string name)

并且我创建了一个类型化的 HttpClient,如下所示:

public class CustomClient {

public CustomClient(HttpClient client,
CustomAuthorizationInfoObject customAuthorizationInfoObject) {
/// use custom authorization info to customize http client
}

public async Task<CustomModel> DoSomeStuffWithClient() {
/// do the stuff
}

}

我可以在程序的 ServiceCollection 中注册这个自定义客户端,如下所示:

services.AddTransient<CustomAuthorizationInfoObject>();
services.AddHttpClient<CustomClient>("DefaultClient");

然后我可以注册这个 CustomClient 的第二个实例,其中包含一些稍微改变的信息:

services.AddHttpClient<CustomClient>("AlternativeAuthInfo", (client) => {
client.DefaultRequestHeaders.Authorization = ...;
});

在程序的其他地方,我现在想要获得一个特定的命名 CustomClient。这证明了障碍。

我可以通过向服务提供商请求 CustomClient 来获取最后添加到服务的任何 CustomClient

调用 IHttpClientFactory.CreateClient("AlternativeAuthInfo"),例如,返回一个 HttpClient,所以我无法访问 CustomClient 中的额外方法,并且没有那里似乎没有任何其他方法可以帮助我。

因此,我该如何着手获得命名的 CustomClient?或者我是否滥用了通过原始扩展方法命名和引用类型化客户端的机会?

最佳答案

我看到有一个 ITypedHttpClientFactory<>可以包装常规 HttpClient 的界面在一个打字的。没有亲自使用过,但这是缺失的部分吗?

例如

/// grab the named httpclient
var altHttpClient = httpClientFactory.CreateClient("AlternativeAuthInfo");

/// get the typed client factory from the service provider
var typedClientFactory = serviceProvider.GetService<ITypedHttpClientFactory<CustomClient>>();

/// create the typed client
var altCustomClient = typedClientFactory.CreateClient(altHttpClient);

关于c# - HttpClientFactory - 通过名称获取命名的类型化客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52201914/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com