当前位置 > 首页 > Asp.net

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

2012-12-7 13:15:00来源:Asp.net

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

5.1 HTTP Message Handlers
5.1 HTTP消息处理器

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

By Mike Wasson | February 13, 2012
作者:Mike Wasson |日期:2012-2-13

A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.
消息处理器是一个接收HTTP请求并返回HTTP响应的类。消息处理器派生于HttpMessageHandler类。

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 handler)(如图5-1所示)。

WebAPI5-1

图中:Request:请求,Delegating Handler:委托处理器,Inner Handler:内部处理器,Response:响应

图5-1. 消息处理器链

Server-Side Message Handlers
服务器端消息处理器

On the server side, the Web API pipeline uses some built-in message handlers:
在服务器端,Web API管线使用一些内建的消息处理器:

  • HttpServer gets the request from the host.
    HttpServer获取从主机发来的请求。
  • HttpRoutingDispatcher dispatches the request based on the route.
    HttpRoutingDispatcher(HTTP路由分发器)基于路由对请求进行分发。
  • HttpControllerDispatcher sends the request to a Web API controller.
    HttpControllerDispatcher(HTTP控制器分发器)将请求发送给一个Web API控制器。

You can add custom handlers to the pipeline. Message handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions). For example, a message handler might:
可以把自定义处理器添加到该管线上。对于在HTTP消息层面上(而不是在控制器动作上)进行操作的交叉关注,消息处理器是很有用的。例如,消息处理器可以:

  • Read or modify request headers.
    读取或修改请求报头。
  • Add a response header to responses.
    对响应添加响应报头。
  • Validate requests before they reach the controller.
    在请求到达控制器之前验证请求。

This diagram shows two custom handlers inserted into the pipeline:
下图显示了插入到管线的两个自定义处理器(见图5-2):

WebAPI5-2

图5-2. 服务器端消息处理器

On the client side, HttpClient also uses message handlers. For more information, see HttpClient Message Handlers.
在客户端,HttpClient也使用消息处理器。更多信息参阅“Http消息处理器”(本系列教程的第3.4小节 — 译者注)。

Custom Message Handlers
自定义消息处理器

To write a custom message handler, derive from System.Net.Http.DelegatingHandler and override the SendAsync method. This method has the following 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.
    处理响应,并将其返回给调用者。

Here is a trivial example:
以下是一个价值不高的示例:

public class MessageHandler1 : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Debug.WriteLine("Process request");
// Call the inner handler.
// 调用内部处理器。
var response = await base.SendAsync(request, cancellationToken);
Debug.WriteLine("Process response");
return response;
}
}

The call to base.SendAsync is asynchronous. If the handler does any work after this call, use the await keyword, as shown.
base.SendAsync的调用是异步的。如果处理器在调用之后有工作要做,需使用await关键字,如上所示。

A delegating handler can also skip the inner handler and directly create the response:
委托处理器也可以跳过内部处理器,并直接创建响应:

public class MessageHandler2 : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Create the response.
// 创建响应。
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello!")
};

// Note: TaskCompletionSource creates a task that does not contain a delegate.
// 注:TaskCompletionSource创建一个不含委托的任务。
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response); // Also sets the task state to "RanToCompletion"
// 也将此任务设置成“RanToCompletion(已完成)”
return tsc.Task;
}
}

If a delegating handler creates the response withou