我只是想創建一個簡單的測驗,我用它DelegateHandlers來實體化 aHttpClient而不帶 Asp.net Core 包。我有 2 個洗掉處理程式
ThrottlingDelegatingHandlerPolicyHttpMessageHandler(來自 Polly 包)
我怎樣才能將兩者結合起來并傳遞給HttpClient?
var policy = HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
var pollyHandler = new PolicyHttpMessageHandler(policy);
var http = new HttpClient(new ThrottlingDelegatingHandler(MaxParallelism, pollyHandler));
以上給了我一個錯誤:System.InvalidOperationException : The inner handler has not been assigned.
PolicyHttpMessageHandler沒有建構式,我可以在其中傳遞innerHandler.
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
您必須InnerHandler在最內部的處理程式中設定HttpClientHandler如下:
var policy = HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
var pollyHandler = new PolicyHttpMessageHandler(policy);
//New line
pollyHandler.InnerHandler = new HttpClientHandler();
var http = new HttpClient(new ThrottlingDelegatingHandler(MaxParallelism, pollyHandler));
您基本上必須在管道中設定下一個處理程式。
供參考:如果沒有指定處理程式,這是 HttpClient 的構造方式
#region Constructors
public HttpClient() : this(new HttpClientHandler())
{
}
public HttpClient(HttpMessageHandler handler) : this(handler, true)
{
}
public HttpClient(HttpMessageHandler handler, bool disposeHandler) : base(handler, disposeHandler)
{
_timeout = s_defaultTimeout;
_maxResponseContentBufferSize = HttpContent.MaxBufferSize;
_pendingRequestsCts = new CancellationTokenSource();
}
#endregion Constructors
班級base在哪里HttpMessageInvoker
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/446788.html
