1
我想記錄請求和HttpClient
與LoggingHandler : DelegatingHandler
響應,但我得到錯誤A task was canceled
。 HttpClient
通過TLS連接。HttpClient與相互TLS和DelegatingHandler記錄請求/響應拋出異常
var httpClient = new HttpClient(MutualTlsHandler());
private WebRequestHandler MutualTlsHandler()
{
var certificateCollection = new X509Certificate2Collection { ClientConfiguration.Certificate };
var mutualTlsHandler = new WebRequestHandler();
mutualTlsHandler.ClientCertificates.AddRange(certificateCollection);
mutualTlsHandler.ServerCertificateValidationCallback = IsValidServerCertificate;
return mutualTlsHandler;
}
這工作就像一個魅力,但我想記錄請求發送。試圖創建一個LoggingHandler
並將其添加到鏈中導致錯誤A task was canceled
。
var httpClient = new HttpClient(new LoggingHandler(MutualTlsHandler())
internal class LoggingHandler : DelegatingHandler
{
public LoggingHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var content = request.Content.ReadAsStringAsync();
return await base.SendAsync(request, cancellationToken);
}
}
我會假定閱讀需要被反繞流使用request.Content.ReadAsStringAsync()
結果,但是這怎麼能實現呢?使用Content.CopyToAsync
進行復制會導致相同的錯誤。
所有幫助表示讚賞。
不幸的是,這給了相同的結果。令人困惑的是,在鏈中可能有多個'DelegatingHandler'讀取內容,但一旦引入'WebRequestHandler',它就會失敗。 –