5
votes

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?

1
How does your question not have more up votes? There is almost nothing on google when you search this.Robert Stokes

1 Answers

6
votes

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.