Having dynamic proxy with HttpClientFactory implementation

后端 未结 2 1676
轮回少年
轮回少年 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:46

    I can do that by inheriting from HttpClientHandler:

    public class ProxyHttpHandler : HttpClientHandler
    {
        private int currentProxyIndex = 0;
    
    private ProxyOptions proxyOptions;
    
    public ProxyHttpHandler(IOptions options)
    {
        proxyOptions = options != null ? options.Value : throw new ArgumentNullException(nameof(options));
        UseProxy = true;
    }
    
    protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var proxy = proxyOptions.Proxies[currentProxyIndex];
        var proxyResolver = new WebProxy(proxy.Host, proxy.Port)
        {
            Credentials = proxy.Credentials
        };
    
        Proxy = proxyResolver;
    
        currentProxyIndex++;
        if(currentProxyIndex >= proxyOptions.Proxies.Count)
            currentProxyIndex = 0;
    
        return base.SendAsync(request, cancellationToken);
    }
    

    }

    Then I register my ProxyHttpHandler and ProxyOptions in IoC:

    public IForksCoreConfigurationBuilder ConfigureProxy(Action options)
    {
        Services.AddOptions().Configure(options);
        Services.AddTransient();
        Services.AddHttpClient()
                .ConfigurePrimaryHttpMessageHandler();
    
        return this;
    }
    

提交回复
热议问题