亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 .NET Core 中使用 HttpClientHandler

如何在 .NET Core 中使用 HttpClientHandler

C#
哈士奇WWW 2021-07-19 16:18:37
我想使用的HttpClientFactory是在.NET 2.1核心可用,但我也想用HttpClientHandler,以利用AutomaticDecompression創建時屬性HttpClients。我很掙扎,因為.AddHttpMessageHandler<>需要一個DelegatingHandler不是HttpClientHandler.有誰知道如何讓這個工作?
查看完整描述

2 回答

?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

其實我沒有使用自動解壓,但實現這一點的方法是正確注冊http客戶端


services.AddHttpClient<MyCustomHttpClient>()

   .ConfigureHttpMessageHandlerBuilder((c) =>

     new HttpClientHandler()

     {

        AutomaticDecompression = System.Net.DecompressionMethods.GZip

     }

   )

   .AddHttpMessageHandler((s) => s.GetService<MyCustomDelegatingHandler>())


查看完整回答
反對 回復 2021-07-31
?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

通過 HttpClientBuilder 的 ConfigurePrimaryHttpMessageHandler() 方法定義主 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;

}


查看完整回答
反對 回復 2021-07-31
  • 2 回答
  • 0 關注
  • 395 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號