C/C++教程

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

本文主要是介绍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();
        }
    }
}

  

这篇关于WebApi HttpClient DelegatingHandler 请求通过一系列管道 请求发送前和响应接收后被执行的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!