【问题标题】:Resolve HttpClient depends on URL (with/without Proxy)解析 HttpClient 依赖于 URL(带/不带代理)
【发布时间】:2021-12-10 12:33:02
【问题描述】:

任务是配置HttpClient的代理依赖于一个URL。例如,如果一个 URL 包含“hostname.com”,则必须设置。

最佳做法是什么?

以下是解决方案吗?

在 DI 中注册不同的 HttpClients 为:

-- Configured typed HttpClients with different proxies for each service
services.AddHttpClient<Service1>().ConfigurePrimaryHttpMessageHandler(GetHttpHandlerSetter(s => s.Service1));
services.AddHttpClient<Service2>().ConfigurePrimaryHttpMessageHandler(GetHttpHandlerSetter(s => s.Service2));

-- Configured named HttpClient without proxy
services.AddHttpClient("NoProxy");

而Service1和Service2会解析IHttpClientFactory:

    public class Service1
{
    readonly IHttpClientFactory _httpClientFactory;

    public IdgwConnectorManager(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }
    
    public void Get(string url)
    {
        if (url...)
        {
            _httpClientFactory.CreateClient(nameof(Service1));
        }
        else
        {
            _httpClientFactory.CreateClient("NoProxy");
        }
    }
}

【问题讨论】:

  • 我会使用 RestSharp 并为此设置一个 Webproxy。如果 webproxy 为空或完整数据的示例将解决问题

标签: c# dotnet-httpclient httpclientfactory


【解决方案1】:

您希望创建一个可以在单个位置进行配置的客户端。因此,您应该创建一个将 http 客户端作为 ctor 参数的服务,在此您可以根据需要对其进行配置。

注意:类型化的客户端非常适合单个后端端点。在代理客户端的情况下,我将使用命名客户端。我会使用字典来存储客户端名称和代理值。

关于如何使用您创建的类型化客户端,一个更强大的解决方案将是这个:

public class Service1
{
    private readonly HttpClient _httpClient;

    public Service1(HttpClient client)
    {
        _httpClient = httpClient;
        // here you can setup headers, base address
    }

    //encapsulate all logic dealing with the endpoint.
}

现在使用 DI,您可以将这个类型化的客户端注入到消费者类中 从那里您可以决定是否需要代理或非代理客户端。

public class ConsumerClass
{
    //The typed client can be injected and consumed directly
    private readonly Service1 _service;

    public ConsumerClass(Service1 service)
    {
        _service= service;
    }
    
    //Consume Service1
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2023-03-09
    • 2011-05-12
    相关资源
    最近更新 更多