gpt4 book ai didi

c# - 如何在 .NET Core 中使用 HttpClientHandler 和 HttpClientFactory

转载 作者:可可西里 更新时间:2023-11-01 07:57:57 24 4
gpt4 key购买 nike

我想使用 HttpClientFactory在 .NET Core 2.1 中可用,但我也想使用 HttpClientHandler利用 AutomaticDecompression创建时的属性 HttpClients .

我很挣扎,因为 .AddHttpMessageHandler<>需要 DelegatingHandler不是HttpClientHandler .

有人知道如何让它工作吗?

谢谢,吉姆

最佳答案

通过 HttpClientBuilderConfigurePrimaryHttpMessageHandler() 方法定义主 HttpMessageHandler 更合适。请参阅下面的示例以配置类型化客户端。

services.AddHttpClient<TypedClient>()
.ConfigureHttpClient((sp, httpClient) =>
{
var options = sp.GetRequiredService<IOptions<SomeOptions>>().Value;
httpClient.BaseAddress = options.Url;
httpClient.Timeout = options.RequestTimeout;
})
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.ConfigurePrimaryHttpMessageHandler(x => new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
})
.AddHttpMessageHandler(sp => sp.GetService<SomeCustomHandler>().CreateAuthHandler())
.AddPolicyHandlerFromRegistry(PollyPolicyName.HttpRetry)
.AddPolicyHandlerFromRegistry(PollyPolicyName.HttpCircuitBreaker);

您还可以通过使用 Polly 库的特殊构建器方法来定义错误处理策略。在此示例中,应预定义策略并将其存储到策略注册表服务中。

public static IServiceCollection AddPollyPolicies(
this IServiceCollection services,
Action<PollyPoliciesOptions> setupAction = null)
{
var policyOptions = new PollyPoliciesOptions();
setupAction?.Invoke(policyOptions);

var policyRegistry = services.AddPolicyRegistry();

policyRegistry.Add(
PollyPolicyName.HttpRetry,
HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(
policyOptions.HttpRetry.Count,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(policyOptions.HttpRetry.BackoffPower, retryAttempt))));

policyRegistry.Add(
PollyPolicyName.HttpCircuitBreaker,
HttpPolicyExtensions
.HandleTransientHttpError()
.CircuitBreakerAsync(
handledEventsAllowedBeforeBreaking: policyOptions.HttpCircuitBreaker.ExceptionsAllowedBeforeBreaking,
durationOfBreak: policyOptions.HttpCircuitBreaker.DurationOfBreak));

return services;
}

关于c# - 如何在 .NET Core 中使用 HttpClientHandler 和 HttpClientFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747749/

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