如何在.NET Core中将HttpClientHandler与HttpClientFactory一起使用

问题描述 投票:0回答:3

我想使用 .NET Core 2.1 中提供的

HttpClientFactory
,但我也想使用
HttpClientHandler
在创建
AutomaticDecompression
时利用
HttpClients
属性。

我很挣扎,因为

.AddHttpMessageHandler<>
需要
DelegatingHandler
而不是
HttpClientHandler

有人知道如何让它发挥作用吗?

谢谢, 吉姆

c# .net-core dotnet-httpclient .net-core-2.1 httpclientfactory
3个回答
35
投票

更正确地通过

HttpMessageHandler
ConfigurePrimaryHttpMessageHandler()
方法定义主要
HttpClientBuilder
。请参阅下面的示例来配置类型化客户端。

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>())

0
投票

对于 .NET Core 7.0:

当您添加 AddHttpClient() 方法时,在 Web 应用程序项目的 program.cs 类中:

builder.Services.AddHttpClient("HttpClientName", c =>{}).ConfigurePrimaryHttpMessageHandler(() =>
      {
          var handler = new HttpClientHandler();
          handler.ServerCertificateCustomValidationCallback =
          HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
          return handler;
      });
© www.soinside.com 2019 - 2024. All rights reserved.