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?
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.
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.
ConfigurePrimaryHttpMessageHandler(IHttpClientBuilder, Func<IServiceProvider,HttpMessageHandler>) Adds a delegate that will be used to configure the primary HttpMessageHandler for a named HttpClient.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With