我没有找到有关它的文档,我认为我当前的解决方案不是最佳的,因为处理程序生命周期不是由HttpClientFactory管理的:
var proxiedHttpClientHandler = new HttpClientHandler() { Proxy = httpProxy };
_createHttpClient = () => HttpClientFactory.Create(proxiedHttpClientHandler);
有更好的解决方案吗?
答案 0 :(得分:4)
将客户端添加到服务集合时,您应该能够在其中配置处理程序
使用命名的客户端方法,我将使用一个常量来保存客户端名称。
public static class NamedHttpClients {
public const string ProxiedClient = "ProxiedClient";
}
从那里只需配置客户端
//...
var serviceCollection = new ServiceCollection();
serviceCollection
.AddHttpClient(NamedHttpClients.ProxiedClient)
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() {
Proxy = httpProxy
});
var services = serviceCollection.BuildServiceProvider();
这样,当通过已解决的IHttpClientFactory
致电客户时
var httpClientFactory = services.GetService<IHttpClientFactory>();
var client = httpClientFactory.CreateClient(NamedHttpClients.ProxiedClient);
返回的客户端将把处理程序与代理一起使用。
答案 1 :(得分:0)
您可以执行以下操作:
private HttpClient ClientFactory()
{
var proxiedHttpClientHandler = new HttpClientHandler(){ UseProxy = true};
proxiedHttpClientHandler.Proxy = new WebProxy("proxy address");
var httpClient = new HttpClient(proxiedHttpClientHandler)
{
BaseAddress = new Uri("uri");
Timeout = 2000; //if you need timeout;
}
}
_createHttpClient = () => ClientFactory();
关于使用工厂与手动实例化httpClient对象的讨论很好here。