Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a HttpClientHandler for named HttpClient using HttpClientFactory

Old code:

Client = new HttpClient(new HttpClientHandler() { DefaultProxyCredentials = CredentialCache.DefaultNetworkCredentials });

// set an default user agent string, some services does not allow emtpy user agents
if (!Client.DefaultRequestHeaders.Contains("User-Agent"))
    Client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0");

Trying to implement the same using the new ASP.NET Core 2.1 HttpClientFactory:

services.AddHttpClient("Default", client =>
        {
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
        }).ConfigurePrimaryHttpMessageHandler(handler => new HttpClientHandler() { DefaultProxyCredentials = CredentialCache.DefaultNetworkCredentials });          

Unfortunately, I get an HTTP 407 (Proxy Auth) error. What I'm doing wrong?

like image 916
Toni Wenzel Avatar asked Jun 26 '18 13:06

Toni Wenzel


People also ask

How do I create an instance of HttpClientFactory?

A basic HttpClientFactory can be instanced via Dependency Injection. First we will need to add the following code to the Startup class within the ConfigureServices method: // File: Startup. cs public class Startup { // Code deleted for brevity.

How can custom handlers be added to HttpClient?

Adding Message Handlers to the Client Pipeline HttpClient client = HttpClientFactory. Create(new Handler1(), new Handler2(), new Handler3()); Message handlers are called in the order that you pass them into the Create method. Because handlers are nested, the response message travels in the other direction.

What is ConfigurePrimaryHttpMessageHandler?

ConfigurePrimaryHttpMessageHandler(IHttpClientBuilder, Func<IServiceProvider,HttpMessageHandler>) Adds a delegate that will be used to configure the primary HttpMessageHandler for a named HttpClient.


1 Answers

It is usually advised to have a static class containing string constants for the names of the clients.

Something like:

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

Then ensure that named client is configured correctly, which in your particular case would look like:

services
    .AddHttpClient(NamedHttpClients.Default, client => {
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
    })
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { 
        DefaultProxyCredentials = CredentialCache.DefaultNetworkCredentials 
    }); 

From there you can get the client from an injected IHttpClientFactory

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

and used as intended.

like image 171
Nkosi Avatar answered Nov 05 '22 14:11

Nkosi