Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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?

like image 611
Bruno Fiorentino Avatar asked Sep 26 '18 21:09

Bruno Fiorentino


People also ask

What is HttpClient proxy?

Advertisements. A Proxy server is an intermediary server between the client and the internet. Proxy servers offer the following basic functionalities − Firewall and network data filtering.

What are the differences between HttpClientFactory and HttpClient?

It has a method CreateClient which returns the HttpClient Object. But in reality, HttpClient is just a wrapper, for HttpMessageHandler. HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood.

What is HttpClientFactory?

IHttpClientFactory is a contract implemented by DefaultHttpClientFactory , an opinionated factory, available since . NET Core 2.1, for creating HttpClient instances to be used in your applications.

How do I use HttpClientHandler with IHttpClientFactory?

In general, HttpClientHandler can be used to configure a specific configuration like custom policy, headers, or security mechanism, compression, certificates, etc. We shall cover the below aspects in this article, Configure HttpClientHandler for Authentication Example: Bearer or Basic.


1 Answers

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.

like image 157
Nkosi Avatar answered Sep 19 '22 11:09

Nkosi