How to use HttpClientHandler with HttpClientFactory in .NET Core

房东的猫 提交于 2019-12-04 01:31:26

Actually I'm not using automatic decompression but the way to achieve this is to properly register http client

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

More properly to define primary HttpMessageHandler via ConfigurePrimaryHttpMessageHandler() method of HttpClientBuilder. See example below to configure typed client how.

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

Also you can define error handling policy via usage of special builders methods of Polly library. In this example policy should be predefined and stored into policy registry service.

  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;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!