How to configure web proxy for HttpClient created directly via HttpClientFactory?

Bruno Fiorentino picture Bruno Fiorentino · Sep 26, 2018 · Viewed 13.5k times · Source
  • By directly I mean without Asp.Net Core IoC/DI helpers.

I didn't find docs about it and I think my current solution isn't optimal because the handler lifecyle isn't managed by the HttpClientFactory:

var proxiedHttpClientHandler = new HttpClientHandler() { Proxy = httpProxy };
_createHttpClient = () => HttpClientFactory.Create(proxiedHttpClientHandler);

Is there a better solution?

Answer

Nkosi picture Nkosi · Sep 26, 2018

When adding the client to the service collection you should be able to configure the handler there

Using the named client approach I'll use a constant to hold the client name.

public static class NamedHttpClients {
    public const string ProxiedClient = "ProxiedClient";
}

From there it is just a matter of configuring the client

//...
var serviceCollection = new ServiceCollection();

serviceCollection
    .AddHttpClient(NamedHttpClients.ProxiedClient)
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { 
        Proxy = httpProxy 
    });

var services = serviceCollection.BuildServiceProvider();

So that when calling the client via a resolved IHttpClientFactory

var httpClientFactory = services.GetService<IHttpClientFactory>();

var client = httpClientFactory.CreateClient(NamedHttpClients.ProxiedClient);

the returned client will use the handler with the proxy.