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

标签 c# .net-core dotnet-httpclient .net-core-2.1 httpclientfactory

我想使用 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/

相关文章:

.net - MsBuild 15 中每个 TargetFramework 的条件

c# - 在 Linux Python 中使用 .NET Core 库

.net-core - dotnet 核心的 String.Copy 替代方案

c# - REST Api 服务器挂起大量请求(使用 c# HttpClient)

c# - 无法确定类型之间关联的主体端

c# - C# ProgressBar 的跨线程问题

c# - 如何向 XDocument 添加多个命名空间声明?

c# - 文档 API : How to use Application Token

c# - 使用 HttpClient 压缩对 asp.net core 2 站点的请求的最佳方法是什么?

c# - 在 HttpClient.SendAsync() 之后无法访问已处置的对象