twitchax / AspNetCore.Proxy

ASP.NET Core Proxies made easy.
MIT License
505 stars 80 forks source link

How to use a WebProxy with the underlying httpclient? #68

Closed paulfryer closed 3 years ago

paulfryer commented 3 years ago

How can I configure the underlying httpClient that is making request use a WebProxy? I need to do something like this:

HttpClientHandler clientHandler = new HttpClientHandler(); clientHandler.Proxy = new WebProxy("10.0.0.22:8000"); using (var httpClient = new HttpClient(clientHandler) { // do stuff with client here. }

paulfryer commented 3 years ago

Actually I just figured it out after reading some of the other issues posted. Looks like you can configure clients in the "ConfigureServices" method, like this:

public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("default").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { Proxy = new WebProxy("http://10.0.0.22:8000") }); ; services.AddControllers(); services.AddMvc(); services.AddProxies(); }

And then you can reference that client configuration using the options builder like this:

var b = HttpProxyOptionsBuilder.Instance.New(); b.WithHttpClientName("default"); b.WithShouldAddForwardedHeaders(true); var options = b.Build(); await this.HttpProxyAsync(requestUrl, options);

twitchax commented 3 years ago

Yep: that is the preferred method!