zoukankan      html  css  js  c++  java
  • WebApi2官网学习记录--HttpClient Message Handlers

    在客户端,HttpClient使用message handle处理request。默认的handler是HttpClientHandler,用来发送请求和获取response从服务端。可以在client pipline中插入自定义的message handler:

    自定义的message handler:

    class MessageHandler1 : DelegatingHandler
    {
        private int _count = 0;
    
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            _count++;
            request.Headers.Add("X-Custom-Header", _count.ToString());
            return base.SendAsync(request, cancellationToken);
        }
    }
    
    class LoggingHandler : DelegatingHandler
    {
        StreamWriter _writer;
    
        public LoggingHandler(Stream stream)
        {
            _writer = new StreamWriter(stream);
        }
    
        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
    
            if (!response.IsSuccessStatusCode)
            {
                _writer.WriteLine("{0}	{1}	{2}", request.RequestUri, 
                    (int)response.StatusCode, response.Headers.Date);
            }
            return response;
        }
    
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _writer.Dispose();
            }
            base.Dispose(disposing);
        }
    }
    

    将Message Handler添加到Client Pipeline

    HttpClient client = HttpClientFactory.Create(new Handler1(), new Handler2(), new Handler3());
    

    Message Handlers调用顺序根据创建时传入的顺序一致,而response消息的传播正好与此相反。

  • 相关阅读:
    CSharp Oracle 登陆
    Oracle基本流程语句
    数据库设计三大范式
    自己总结一些操作数据库的方法
    常用数据库取得前几行的方法
    Intellij idea创建javaWeb以及Servlet简单实现
    idea发布到tomcat缺少jar
    回调函数
    spring笔记
    动态代理
  • 原文地址:https://www.cnblogs.com/goodlucklzq/p/4480274.html
Copyright © 2011-2022 走看看