我想使用.NET HttpClientFactory
Core 2.1 中提供的 .NET Core 2.1 但我也想在创建.HttpClientHandler
AutomaticDecompression
HttpClients
我很挣扎,因为.AddHttpMessageHandler<>
需要 aDelegatingHandler
不是HttpClientHandler
.
有谁知道如何让它工作?
谢谢,吉姆
我想使用.NET HttpClientFactory
Core 2.1 中提供的 .NET Core 2.1 但我也想在创建.HttpClientHandler
AutomaticDecompression
HttpClients
我很挣扎,因为.AddHttpMessageHandler<>
需要 aDelegatingHandler
不是HttpClientHandler
.
有谁知道如何让它工作?
谢谢,吉姆
通过 HttpClientBuilder 的 ConfigurePrimaryHttpMessageHandler() 方法更恰当地定义主 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;
}
其实我没有使用自动解压,但实现这一点的方法是正确注册http客户端
services.AddHttpClient<MyCustomHttpClient>()
.ConfigureHttpMessageHandlerBuilder((c) =>
new HttpClientHandler()
{
AutomaticDecompression = System.Net.DecompressionMethods.GZip
}
)
.AddHttpMessageHandler((s) => s.GetService<MyCustomDelegatingHandler>())