【ASP.NET Web API教程】3.4 HttpClient消息处理器

简介: 原文:【ASP.NET Web API教程】3.4 HttpClient消息处理器注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。 3.4 HttpClient Message Handlers 3.
原文: 【ASP.NET Web API教程】3.4 HttpClient消息处理器

注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。

3.4 HttpClient Message Handlers
3.4 HttpClient消息处理器

本文引自:http://www.asp.net/web-api/overview/web-api-clients/httpclient-message-handlers

By Mike Wasson | October 1, 2012
作者:Mike Wasson | 日期:2012-10-1

A message handler is a class that receives an HTTP request and returns an HTTP response.
消息处理器是一个接收HTTP请求并返回HTTP响应的类。

Typically, a series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.
典型地,一系列消息处理器会链接在一起。第一个处理器接收HTTP请求,进行某些处理,将此请求传给下一个处理器。在处理链的某个点上创建响应,并进行回溯。这种模式称为委托(delegating)处理器(如图3-7所示)。

WebAPI3-7

图3-7. 消息处理链及委托处理器

On the client side, the HttpClient class uses a message handler to process requests. The default handler is HttpClientHandler, which sends the request over the network and gets the response from the server. You can insert custom message handlers into the client pipeline:
在客户端,HttpClient类使用消息处理器处理请求。默认的处理器是HttpClientHandler,它在网络上发送请求,并从服务器获取响应。你可以把自定义消息处理器插入到这种客户端管线之中(如图3-8所示)。

WebAPI3-8

图3-8. 消息处理管线

ASP.NET Web API also uses message handlers on the server side. For more information, see HTTP Message Handlers.
ASP.NET Web API也使用服务器端的消息处理器,更多信息参阅“HTTP消息处理器”(本系列教程第5.1小节 — 译者注)。

Custom Message Handlers
自定义消息处理器

To write a custom message handler, derive from System.Net.Http.DelegatingHandler and override the SendAsync method. Here is the method signature:
要编写自定义消息处理器,需从System.Net.Http.DelegatingHandler进行派生,并重写SendAsync方法。以下是该方法的签名:

Task<HttpResponseMessage> SendAsync(
    HttpRequestMessage request, CancellationToken cancellationToken);

The method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:
该方法以HttpRequestMessage作为输入,并异步地返回一个HttpResponseMessage。一种典型的实现(流程)如下:

  1. Process the request message.
    处理请求消息。
  2. Call base.SendAsync to send the request to the inner handler.
    调用base.SendAsync将请求发送给内部处理器。
  3. The inner handler returns a response message. (This step is asynchronous.)
    内部处理器返回一条响应消息。(这一步是异步的。)
  4. Process the response and return it to the caller.
    处理响应,并把它返回给客户端。

The following example shows a message handler that adds a custom header to the outgoing request:
以下示例展示了一个消息处理器,它把一个自定义报头添加到输出请求:

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); 
    } 
}

The call to base.SendAsync is asynchronous. If the handler does any work after this call, use the await keyword to resume execution after the method completes. The following example shows a handler that logs error codes. The logging itself is not very interesting, but the example shows how to get at the response inside the handler.
base.SendAsync的调用是异步的。如果处理器在调用之后还要做一些工作,需使用await关键字,以便在方法完成之后继续执行。以下示例展示了一个对错误码进行日志的处理器。如何进行日志没多大关系,但此例展示了如何得到处理器内部的响应。

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}\t{1}\t{2}", request.RequestUri,  
                (int)response.StatusCode, response.Headers.Date); 
        } 
        return response; 
    } 
    protected override void Dispose(bool disposing) 
    { 
        if (disposing) 
        { 
            _writer.Dispose(); 
        } 
        base.Dispose(disposing); 
    } 
}

Adding Message Handlers to the Client Pipeline
将消息处理器添加到客户端管线

To add custom handlers to HttpClient, use the HttpClientFactory.Create method:
要将自定义处理器添加到HttpClient,需使用HttpClientFactory.Create方法:

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

Message handlers are called in the order that you pass them into the Create method. Because handlers are nested, the response message travels in the other direction. That is, the last handler is the first to get the response message.
消息处理器是按照把它们传递给Create方法中的顺序来调用的。因此处理器是内嵌的,响应消息以反方向传递。即,最后一个处理器首先得到响应消息。

看完此文如果觉得有所收获,恳请给个推荐

目录
相关文章
|
2月前
|
中间件 Go
Golang | Gin:net/http与Gin启动web服务的简单比较
总的来说,`net/http`和 `Gin`都是优秀的库,它们各有优缺点。你应该根据你的需求和经验来选择最适合你的工具。希望这个比较可以帮助你做出决策。
90 35
|
6月前
|
开发框架 前端开发 JavaScript
ASP.NET Web Pages - 教程
ASP.NET Web Pages 是一种用于创建动态网页的开发模式,采用HTML、CSS、JavaScript 和服务器脚本。本教程聚焦于Web Pages,介绍如何使用Razor语法结合服务器端代码与前端技术,以及利用WebMatrix工具进行开发。适合初学者入门ASP.NET。
|
8月前
|
XML JSON API
ServiceStack:不仅仅是一个高性能Web API和微服务框架,更是一站式解决方案——深入解析其多协议支持及简便开发流程,带您体验前所未有的.NET开发效率革命
【10月更文挑战第9天】ServiceStack 是一个高性能的 Web API 和微服务框架,支持 JSON、XML、CSV 等多种数据格式。它简化了 .NET 应用的开发流程,提供了直观的 RESTful 服务构建方式。ServiceStack 支持高并发请求和复杂业务逻辑,安装简单,通过 NuGet 包管理器即可快速集成。示例代码展示了如何创建一个返回当前日期的简单服务,包括定义请求和响应 DTO、实现服务逻辑、配置路由和宿主。ServiceStack 还支持 WebSocket、SignalR 等实时通信协议,具备自动验证、自动过滤器等丰富功能,适合快速搭建高性能、可扩展的服务端应用。
463 3
|
6月前
|
运维 前端开发 C#
一套以用户体验出发的.NET8 Web开源框架
一套以用户体验出发的.NET8 Web开源框架
188 7
一套以用户体验出发的.NET8 Web开源框架
|
5月前
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
87 14
|
6月前
|
开发框架 搜索推荐 算法
一个包含了 50+ C#/.NET编程技巧实战练习教程
一个包含了 50+ C#/.NET编程技巧实战练习教程
209 18
|
6月前
|
缓存 算法 安全
精选10款C#/.NET开发必备类库(含使用教程),工作效率提升利器!
精选10款C#/.NET开发必备类库(含使用教程),工作效率提升利器!
192 12
|
7月前
|
开发框架 .NET 程序员
驾驭Autofac,ASP.NET WebApi实现依赖注入详细步骤总结
Autofac 是一个轻量级的依赖注入框架,专门为 .NET 应用程序量身定做,它就像是你代码中的 "魔法师",用它来管理对象的生命周期,让你的代码更加模块化、易于测试和维护
208 4
驾驭Autofac,ASP.NET WebApi实现依赖注入详细步骤总结
|
6月前
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。
|
8月前
|
存储 NoSQL API
.NET NoSQL 嵌入式数据库 LiteDB 使用教程
.NET NoSQL 嵌入式数据库 LiteDB 使用教程~
279 0