如何为直接通过HttpClientFactory创建的HttpClient配置Web代理?

时间:2018-09-26 21:12:55

标签: c# .net .net-core dotnet-httpclient httpclientfactory

  • 直接是指没有Asp.Net Core IoC / DI帮助程序。

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

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

有更好的解决方案吗?

2 个答案:

答案 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