2016-03-11 46 views
1

我想記錄請求和HttpClientLoggingHandler : DelegatingHandler響應,但我得到錯誤A task was canceledHttpClient通過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進行復制會導致相同的錯誤。

所有幫助表示讚賞。

回答

0

您是否試過在此nuget包中使用HttpClientFactoryhttps://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/

隨着加那我認爲你可以這樣做:

HttpClientFactory.Create(mutualTlsHandler, loggingHandler); 
+0

不幸的是,這給了相同的結果。令人困惑的是,在鏈中可能有多個'DelegatingHandler'讀取內容,但一旦引入'WebRequestHandler',它就會失敗。 –