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

55

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

我遇到了麻烦,因为.AddHttpMessageHandler<>需要一个DelegatingHandler而不是HttpClientHandler

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

谢谢, Jim

2个回答

36

通过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;
}

22

实际上,我没有使用自动解压缩,但实现这一功能的方法是正确注册HTTP客户端。

services.AddHttpClient<MyCustomHttpClient>()
   .ConfigureHttpMessageHandlerBuilder((c) =>
     new HttpClientHandler()
     {
        AutomaticDecompression = System.Net.DecompressionMethods.GZip
     }
   )
   .AddHttpMessageHandler((s) => s.GetService<MyCustomDelegatingHandler>())

22
对我来说没有用。不得不使用以下代码: .ConfigureHttpMessageHandlerBuilder(builder => { builder.PrimaryHandler = new HttpClientHandler() { UseDefaultCredentials = true }; builder.Build(); }) - Georgi Georgiev
4
更恰当地使用ConfigurePrimaryHttpMessageHandler()方法。 - trueboroda
5
您的解决方案中对ConfigureHttpMessageHandlerBuilder的第一个调用完全没有作用,该方法需要一个Action<T>,而您只是返回了一个立即被丢弃的值: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.httpclientbuilderextensions.configurehttpmessagehandlerbuilder?view=dotnet-plat-ext-3.0 - Sharparam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接