WebApi HttpClient DelegatingHandler 请求通过一系列管道 请求发送前和响应接收后被执行

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WebApi
{
class Program
{
    static void Main(string[] args)
    {
        HttpMessageHandler handler = new HttpClientHandler();
        handler = new BazHandler { InnerHandler = handler };
        handler = new BarHandler { InnerHandler = handler };
        handler = new FooHandler { InnerHandler = handler };
        HttpClient httpClient = new HttpClient(handler);
        HttpResponseMessage  response = httpClient.GetAsync("http://www.asp.net").Result;
        Console.Read();
    }
}
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebApi
{
    public class ClientHandlerBase : DelegatingHandler
    {
        protected virtual void BeforeSendRequest(HttpRequestMessage request)
        {
            Console.WriteLine(string.Format("{0}.BeforeSendRequest()", this.GetType().Name));
        }

        protected virtual void AfterReceiveResponse(HttpResponseMessage response)
        {
            Console.WriteLine(string.Format("{0}.AfterReceiveResponse()", this.GetType().Name));
        }

        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            this.BeforeSendRequest(request);
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
            this.AfterReceiveResponse(response);
            return response;
        }
    }

    public class FooHandler : ClientHandlerBase
    { }

    public class BarHandler : ClientHandlerBase
    { }

    public class BazHandler : ClientHandlerBase
    { }
}

  

也可以通过 Factory来创建

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WebApi
{
    class Program
    {
        static void Main(string[] args)
        {

            HttpClient httpClient = HttpClientFactory.Create(new FooHandler(), new BarHandler(), new BazHandler());
            HttpResponseMessage response = httpClient.GetAsync("http://www.asp.net").Result;
            Console.Read();
        }
    }
}

  

posted @ 2021-12-27 05:30  zq爱生活爱代码  阅读(48)  评论(0编辑  收藏  举报