具有Mutual TLS和DelegatingHandler的HttpClient用于记录请求/响应抛出异常

时间:2016-03-11 12:35:25

标签: c# dotnet-httpclient

我想使用HttpClient记录LoggingHandler : DelegatingHandler的请求和响应,但收到错误A task was canceledHttpClient通过TLS连接。

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进行复制会导致相同的错误。

所有帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用此nuget包中的HttpClientFactoryhttps://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/

添加后我认为你可以这样做:

HttpClientFactory.Create(mutualTlsHandler, loggingHandler);