在项目中自定义了一个HttpClientLoggingHandler
用来记录httpclient
发送请求的输入输出日志。运行后调用了几次抛出异常
The 'InnerHandler' property must be null. 'DelegatingHandler' instances provided to 'HttpMessageHandlerBuilder' must not be reused or cached.
Handler: 'EM.Passport.Badge.Service.Infrastructure.WebApi.HttpClientLoggingHandler'
检查代码发现自己在注入HttpClientLoggingHandler
时,生命周期选择的是AddSingleton
。而异常错误很明显说明管道中的DelegatingHandler
不能复用或缓存。所以将注入的生命周期修改为AddScoped
。
问题解决!
附 HttpClientLoggingHandler 代码
/// <summary>
/// HttpClient 日志Handler
/// </summary>
public class HttpClientLoggingHandler : DelegatingHandler
{
private readonly ILogger<HttpClientLoggingHandler> _logger;
public HttpClientLoggingHandler(ILogger<HttpClientLoggingHandler> logger)
{
_logger = logger;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
//logging
try
{
_logger.LogInformation($"requestUrl:{request.RequestUri}。request:{await request.Content.ReadAsStringAsync()}。response:{await response.Content.ReadAsStringAsync()}");
}
catch (Exception ex)
{
_logger.LogInformation($"requestUrl:{request.RequestUri}。request:{await request.Content.ReadAsStringAsync()}。logging error:{ex.Message}");
}
return response;
}