Some of our services have to make outbound HTTP requests to an integration partner via a proxy. In this post, I’m going to show how to configure the proxy when registering HTTP clients. This will work with all types of HTTP clients, see here for more information on what they are.
Let’s say we want to register a HTTP client with a base address “https://sample.client.url.com”. All requests by this client will need to go through a proxy at “https://sample.proxy.url.com”. In the ConfigureServices in Startup.cs, add the HTTP client as followed.
public void ConfigureServices(IServiceCollection services)
{
// Other services configurations go here
services.AddHttpClient("SampleClient", client =>
{
client.BaseAddress = new Uri("https://sample.client.url.com");
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
Proxy = new WebProxy("https://sample.proxy.url.com")
});
}