我想使用HttpClient
记录LoggingHandler : DelegatingHandler
的请求和响应,但收到错误A task was canceled
。 HttpClient
通过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
进行复制会导致相同的错误。
所有帮助表示赞赏。
答案 0 :(得分:0)
您是否尝试过使用此nuget包中的HttpClientFactory
:https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/。
添加后我认为你可以这样做:
HttpClientFactory.Create(mutualTlsHandler, loggingHandler);