zoukankan      html  css  js  c++  java
  • 项目总结一:HttpClient DelegatingHandler管道扩展 生命周期问题

    在项目中自定义了一个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;
            }
    
    
  • 相关阅读:
    解题报告:luogu P1156
    解题报告:AT3605
    矩阵乘法与斐波那契数列
    九、模块
    八、异常
    七、文件处理
    六、对象和内存分析
    五、函数和内存分析
    四、控制语句
    三、序列
  • 原文地址:https://www.cnblogs.com/gt1987/p/14548279.html
Copyright © 2011-2022 走看看