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

时间:2018-06-07 18:17:15

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

我想使用.NET Core 2.1中提供的HttpClientFactory,但我还想在创建HttpClientHandler时使用AutomaticDecompression来使用HttpClients属性。

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

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

谢谢, 吉姆

2 个答案:

答案 0 :(得分:7)

实际上我没有使用自动解压缩,但实现此目的的方法是正确注册http客户端

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

答案 1 :(得分:0)

更正确地通过HttpClientBuilder的ConfigurePrimaryHttpMessageHandler()方法定义主HttpMessageHandler。请参见下面的示例以配置类型化客户端的方式。

  services.AddHttpClient<TypedClient>()
                      .ConfigureHttpClient((sp, httpClient) =>
                      {

                          var options= sp.GetRequiredService<IOptions<SomeOptions>>().Value;
                          httpClient.BaseAddress = platformEndpointOptions.Url;
                          httpClient.Timeout = platformEndpointOptions.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;
    }
相关问题