原文:【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所示)。

图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所示)。

图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方法中的顺序来调用的。因此处理器是内嵌的,响应消息以反方向传递。即,最后一个处理器首先得到响应消息。

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

【ASP.NET Web API教程】3.4 HttpClient消息处理器的更多相关文章

  1. 【ASP.NET Web API教程】3.2 通过.NET客户端调用Web API(C#)

    原文:[ASP.NET Web API教程]3.2 通过.NET客户端调用Web API(C#) 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的 ...

  2. 【ASP.NET Web API教程】3 Web API客户端

    原文:[ASP.NET Web API教程]3 Web API客户端 Chapter 3: Web API Clients 第3章 Web API客户端 本文引自:http://www.asp.net ...

  3. 【ASP.NET Web API教程】5.4 ASP.NET Web API批处理器

    原文:[ASP.NET Web API教程]5.4 ASP.NET Web API批处理器 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内容. ...

  4. 【ASP.NET Web API教程】5.1 HTTP消息处理器

    原文:[ASP.NET Web API教程]5.1 HTTP消息处理器 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内容. 5.1 HTTP ...

  5. 【ASP.NET Web API教程】3.3 通过WPF应用程序调用Web API(C#)

    原文:[ASP.NET Web API教程]3.3 通过WPF应用程序调用Web API(C#) 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的 ...

  6. 【ASP.NET Web API教程】2.4 创建Web API的帮助页面

    原文:[ASP.NET Web API教程]2.4 创建Web API的帮助页面 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容. 2.4 ...

  7. 【ASP.NET Web API教程】2.3.7 创建首页

    原文:[ASP.NET Web API教程]2.3.7 创建首页 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容. Part 7: Crea ...

  8. 【ASP.NET Web API教程】2.3.6 创建产品和订单控制器

    原文:[ASP.NET Web API教程]2.3.6 创建产品和订单控制器 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容. Part 6 ...

  9. 【ASP.NET Web API教程】2.3.5 用Knockout.js创建动态UI

    原文:[ASP.NET Web API教程]2.3.5 用Knockout.js创建动态UI 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容 ...

随机推荐

  1. Vedis - An Embeddable Datastore Engine

    Vedis - An Embeddable Datastore Engine     An Embeddable Datastore Engine         Tweet        Follo ...

  2. SilkTest天龙八部系列5-类的属性

    SilkTest的面向对象机制让用户可以为类定义属性,用property语句实现.除此以外用户在类中还可以定义成员变量和不可变的setting属性.也就是是说Silktest类中可以有以下三种属性/变 ...

  3. Vi/VIM键盘图, Vi/vim学习图

    Vi/vim学习图 引用: Vi键盘图片可视化教程 http://www.cnblogs.com/me115/archive/2010/11/16/1878295.html 网上的文章易流失.感谢分享 ...

  4. C++自增和自减运算符(--和++)

    在C和C++中,常在表达式中使用自增(++)和自减(--)运算符,他们的作用是使变量的值增1或减1,如:++i(在使用i之前,先使i的值加1,如果i的原值为3,则执行j=++i后,j的值为4)--i ...

  5. BZOJ 3039: 玉蟾宫( 悬线法 )

    最大子矩阵...悬线法..时间复杂度O(nm) 悬线法就是记录一个H向上延伸的最大长度(悬线), L, R向左向右延伸的最大长度, 然后通过递推来得到. ----------------------- ...

  6. 自定义的Server

    自定义的Server 我们在上面对ASP.NET Core默认提供的具有跨平台能力的KestrelServer进行了详细介绍(<聊聊ASP.NET Core默认提供的这个跨平台的服务器——Kes ...

  7. 高级特性(8)- JavaBean构件

    8.1 为何使用Bean8.2 编写Bean的过程8.3 使用Bean构造应用程序 8.3.1 将Bean打包成JAR文件 8.3.2 在开发环境中组合Bean8.4 Bean属性与事件的命名模式8. ...

  8. 数学之路-python计算实战(14)-机器视觉-图像增强(直方图均衡化)

    我们来看一个灰度图像,让表示灰度出现的次数,这样图像中灰度为 的像素的出现概率是  是图像中全部的灰度数, 是图像中全部的像素数,  实际上是图像的直方图,归一化到 . 把  作为相应于  的累计概率 ...

  9. UVA 718 - Skyscraper Floors(数论)

    UVA 718 - Skyscraper Floors 题目链接 题意:在一个f层高的楼上,有e个电梯,每一个电梯有x,y表示y + k * x层都能够到,如今要问从a层是否能到达b层(中间怎么换乘电 ...

  10. 凤凰OS

    看看这个http://www.phoenixos.com 是不是你想要的     --- 共有 5 条评论 --- Entity回复 @Leaybc : 今天装的凤凰os,有很多的BUG整天还不错.  ...