5

旧代码:

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(代理身份验证)错误。我做错了什么?

4

1 回答 1

6

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

就像是:

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

并按预期使用。

于 2018-06-26T14:18:13.683 回答