gpt4 book ai didi

asp.net - 如何使用 HttpClientFactory 为命名的 HttpClient 定义 HttpClientHandler

转载 作者:行者123 更新时间:2023-12-03 21:23:15 27 4
gpt4 key购买 nike

旧代码:

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

最佳答案

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

就像是:

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

从那里您可以从注入(inject)的 IHttpClientFactory 获取客户端
var client = httpClientFactory.CreateClient(NamedHttpClients.Default);

并按预期使用。

关于asp.net - 如何使用 HttpClientFactory 为命名的 HttpClient 定义 HttpClientHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51044545/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com