如何使用HttpClientFactory为命名HttpClient定义HttpClientHandler

时间:2018-06-26 13:50:05

标签: asp.net asp.net-core .net-core dotnet-httpclient httpclientfactory

旧代码:

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");

尝试使用新的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 });          

很不幸,我收到HTTP 407(代理验证)错误。 我在做什么错了?

1 个答案:

答案 0 :(得分:2)

通常建议使用一个静态类,其中包含用于客户端名称的字符串常量。

类似的东西:

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

然后确保正确配置了命名客户端,在您的特殊情况下,外观如下:

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

从那里您可以从注入的IHttpClientFactory那里获得客户

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

并按预期使用。