WebApi HttpClient DelegatingHandler 请求通过一系列管道 请求发送前和响应接收后被执行
2021/12/27 6:07:08
本文主要是介绍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 请求通过一系列管道 请求发送前和响应接收后被执行的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-05Easysearch 可搜索快照功能,看这篇就够了
- 2025-01-04BOT+EPC模式在基础设施项目中的应用与优势
- 2025-01-03用LangChain构建会检索和搜索的智能聊天机器人指南
- 2025-01-03图像文字理解,OCR、大模型还是多模态模型?PalliGema2在QLoRA技术上的微调与应用
- 2025-01-03混合搜索:用LanceDB实现语义和关键词结合的搜索技术(应用于实际项目)
- 2025-01-03停止思考数据管道,开始构建数据平台:介绍Analytics Engineering Framework
- 2025-01-03如果 Azure-Samples/aks-store-demo 使用了 Score 会怎样?
- 2025-01-03Apache Flink概述:实时数据处理的利器
- 2025-01-01使用 SVN合并操作时,怎么解决冲突的情况?-icode9专业技术文章分享
- 2025-01-01告别Anaconda?试试这些替代品吧