12
  • 直接我的意思是没有 Asp.Net Core IoC/DI 助手。

我没有找到有关它的文档,并且我认为我当前的解决方案不是最佳的,因为处理程序生命周期不是由 HttpClientFactory 管理的:

var proxiedHttpClientHandler = new HttpClientHandler() { Proxy = httpProxy };
_createHttpClient = () => HttpClientFactory.Create(proxiedHttpClientHandler);

有更好的解决方案吗?

4

2 回答 2

17

将客户端添加到服务集合时,您应该能够在那里配置处理程序

使用命名客户端方法,我将使用一个常量来保存客户端名称。

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

返回的客户端将使用带有代理的处理程序。

于 2018-09-26T21:39:02.857 回答
7

你可以这样做:

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 对象的很好的讨论。

于 2018-09-26T21:31:19.063 回答