Having dynamic proxy with HttpClientFactory implementation

后端 未结 2 1702
轮回少年
轮回少年 2021-01-06 08:15

I have Asp.Net Core WebApi. I am making Http requests according to HttpClientFactory pattern. Here is my sample code:

public void ConfigureServ         


        
2条回答
  •  盖世英雄少女心
    2021-01-06 08:47

    There is no way to change the any of the properties of HttpClientHandler or to assign a new version of HttpClientHandler to an existing HttpClient after it is instantiated. As such, it is then impossible to have a dynamic proxy for a particular HttpClient: you can only specify one proxy.

    The correct way to achieve this is to use named clients, instead, and define a client for each proxy endpoint. Then, you'll need to inject IHttpClientFactory and pick one of the proxies to use, requesting the named client that implements that.

    services.AddHttpClient("MyServiceProxy1").ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = true
        };
    });
    
    services.AddHttpClient("MyServiceProxy2").ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler
        {
            Proxy = new WebProxy("http://127.0.0.1:8889"),
            UseProxy = true
        };
    });
    
    ...
    

    Then:

    public class MyService : IMyInterface
    {
        private readonly HttpClient _client;
    
        public MyService(IHttpClientFactory httpClientFactory)
        {
            _client = httpClientFactory.CreateClient("MyServiceProxy1");
        }
    
        public async Task CallHttpEndpoint()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "www.customUrl.com");
            var response = await _client.SendAsync(request);
            ...
        }
    }
    

提交回复
热议问题