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;
            }
    
    
  • 相关阅读:
    Android 锁屏 临时屏蔽
    单编译framework相关模块
    02
    pad 强制加载 Hdpi资源 (2.3 dpi < 240)
    设置form的默认按钮
    How to Be a Good Graduate Student
    我怕你们急于求成
    希腊字母读音表
    数据库札记(二)
    Ubuntu 9.04下jdk的安装与配置
  • 原文地址:https://www.cnblogs.com/gt1987/p/14548279.html
Copyright © 2011-2022 走看看