I have Asp.Net Core WebApi
. I am making Http requests according to HttpClientFactory pattern. Here is my sample code:
public void ConfigureServ
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;
}