本文引自: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所示)。

圖中:Request:請求,Delegating Handler:委托處理器,Inner Handler:内部處理器,Response:響應
圖5-1. 消息處理器鍊
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):
圖5-2. 伺服器端消息處理器
在用戶端,HttpClient也使用消息處理器。更多資訊參閱“Http消息處理器”(本系列教程的第3.4小節 — 譯者注)。
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方法。該方法有以下簽名:
The method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:
該方法以HttpRequestMessage作為輸入參數,并異步地傳回一個HttpResponseMessage。典型的實作要做以下事:
Process the request message.
處理請求消息。
Call base.SendAsync to send the request to the inner handler.
調用base.SendAsync将該請求發送給内部處理器。
The inner handler returns a response message. (This step is asynchronous.)
内部處理器傳回響應消息。(此步是異步的。)
Process the response and return it to the caller.
處理響應,并将其傳回給調用者。
Here is a trivial example:
以下是一個價值不高的示例:
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:
委托處理器也可以跳過内部處理器,并直接建立響應:
If a delegating handler creates the response without calling base.SendAsync, the request skips the rest of the pipeline. This can be useful for a handler that validates the request (creating an error response).
如果委托處理器未調用base.SendAsync建立了響應,該請求會跳過管線的其餘部分(如圖5-3所示)。這對驗證請求(建立錯誤消息)的處理器,可能是有用的。
圖5-3. 被跳過的處理器
To add a message handler on the server side, add the handler to the HttpConfiguration.MessageHandlers collection. If you used the "ASP.NET MVC 4 Web Application" template to create the project, you can do this inside the WebApiConfig class:
要在伺服器端添加消息處理器,需要将該處理器添加到HttpConfiguration.MessageHandlers集合。如果建立項目用的是“ASP.NET MVC 4 Web應用程式”模闆,你可以在WebApiConfig類中做這件事:
Message handlers are called in the same order that they appear in MessageHandlers collection. Because they are nested, the response message travels in the other direction. That is, the last handler is the first to get the response message.
消息處理器是按它們在MessageHandlers集合中出現的順序來調用的。因為它們是内嵌的,響應消息以反方向運作,即,最後一個處理器最先得到響應消息。
Notice that you don't need to set the inner handlers; the Web API framework automatically connects the message handlers.
注意,不需要設定内部處理器;Web API架構會自動地連接配接這些消息處理器。
如果是“自托管”(本系列教程的第8.1小節 — 譯者注)的,需要建立一個HttpSelfHostConfiguration類的執行個體,并将處事器添加到MessageHandlers集合。
Now let's look at some examples of custom message handlers.
現在,讓我們看一些自定義消息處理器的例子。
X-HTTP-Method-Override is a non-standard HTTP header. It is designed for clients that cannot send certain HTTP request types, such as PUT or DELETE. Instead, the client sends a POST request and sets the X-HTTP-Method-Override header to the desired method. For example:
X-HTTP-Method-Override是一個非标準的HTTP報頭。這是為不能發送某些HTTP請求類型(如PUT或DELETE)的用戶端而設計的。是以,用戶端可以發送一個POST請求,并把X-HTTP-Method-Override設定為所希望的方法(意即,對于不能發送PUT或DELETE請求的用戶端,可以讓它發送POST請求,然後用X-HTTP-Method-Override把這個POST請求重寫成PUT或DELETE請求 — 譯者注)。例如:
Here is a message handler that adds support for X-HTTP-Method-Override:
以下是添加了X-HTTP-Method-Override支援的一個消息處事器:
In the SendAsync method, the handler checks whether the request message is a POST request, and whether it contains the X-HTTP-Method-Override header. If so, it validates the header value, and then modifies the request method. Finally, the handler calls base.SendAsync to pass the message to the next handler.
在SendAsync方法中,處理器檢查了該請求消息是否是一個POST請求,以及它是否含有X-HTTP-Method-Override報頭。如果是,它會驗證報頭值,然後修改請求方法。最後,處理器調用base.SendAsync,把消息傳遞給下一下處事器。
When the request reaches the HttpControllerDispatcher class, HttpControllerDispatcher will route the request based on the updated request method.
當請求到達HttpControllerDispatcher類時,HttpControllerDispatcher會根據這個已被更新的請求方法對該請求進行路由。
Here is a message handler that adds a custom header to every response message:
以下是一個把自定義報頭添加到每個響應消息的消息處理器:
First, the handler calls base.SendAsync to pass the request to the inner message handler. The inner handler returns a response message, but it does so asynchronously using a Task<T> object. The response message is not available until base.SendAsync completes asynchronously.
首先,該處理器調用base.SendAsync把請求傳遞給内部消息處理器。内部處理器傳回一條響應消息,但它是用Task<T>對象異步地做這件事的。在base.SendAsync異步完成之前,響應消息是不可用的。
This example uses the await keyword to perform work asynchronously after SendAsync completes. If you are targeting .NET Framework 4.0, use the Task.ContinueWith method:
這個示例使用了await關鍵字,以便在SendAsync完成之後異步地執行任務。如果你的目标架構是.NET Framework 4.0,需使用Task.ContinueWith方法:
Some web services require clients to include an API key in their request. The following example shows how a message handler can check requests for a valid API key:
有些Web服務需要用戶端在其請求中包含一個API鍵。以下示例示範一個消息處理器如何針對一個有效的API鍵來檢查請求:
This handler looks for the API key in the URI query string. (For this example, we assume that the key is a static string. A real implementation would probably use more complex validation.) If the query string contains the key, the handler passes the request to the inner handler.
該處理器在URI查詢字元串中查找API鍵(對此例而言,我們假設鍵是一個靜态字元串。一個真實的實作可能會使用更複雜的驗證。)如果查詢字元串包含這個鍵,該處理便把請求傳遞給内部處理器。
If the request does not have a valid key, the handler creates a response message with status 403, Forbidden. In this case, the handler does not call base.SendAsync, so the inner handler never receives the request, nor does the controller. Therefore, the controller can assume that all incoming requests have a valid API key.
如果請求沒有一個有效的鍵,該處理器便建立一個狀态為“403 — 拒絕通路”的響應消息。在這種情況下,該處理器不會調用base.SendAsync,于是,内部處理不會收到這個請求,控制器也就不會收到這個請求了。是以,控制器可以假設所有輸入請求都有一個有效的API鍵。
If the API key applies only to certain controller actions, consider using an action filter instead of a message handler. Action filters run after URI routing is performed.
如果API鍵僅運用于某些控制器動作,請考慮使用動作過濾器,而不是消息處理器。動作過濾在URI路由完成之後運作。
Handlers in the HttpConfiguration.MessageHandlers collection apply globally.
HttpConfiguration.MessageHandlers集合中的處理器是全局運用的。
Alternatively, you can add a message handler to a specific route when you define the route:
另一種辦法是,在定義路由時,對一個特定的路由添加消息處理器:
In this example, if the request URI matches "Route2", the request is dispatched to MessageHandler2. The following diagram shows the pipeline for these two routes:
在這個例子中,如果請求的URI與“Route2”比對,該請求被分發給MessageHandler2。圖5-4展示了這兩個路由的管線:
圖5-4. 單路由消息處理器
Notice that MessageHandler2 replaces the default HttpControllerDispatcher. In this example, MessageHandler2 creates the response, and requests that match "Route2" never go to a controller. This lets you replace the entire Web API controller mechanism with your own custom endpoint.
注意,MessageHandler2替換了預設的HttpControllerDispatcher。在這個例子中,MessageHandler2建立響應,而與“Route2”比對的請求不會到達控制器。這讓你可以用自己的自定義端點來替換整個Web API控制器機制。
Alternatively, a per-route message handler can delegate to HttpControllerDispatcher, which then dispatches to a controller.
另一種辦法是,單路由消息處理器可以委托給HttpControllerDispatcher,然後由它來分發給控制器(如圖5-5所示)。
圖5-5. 将消息處理器委托給HttpControllerDispatcher
The following code shows how to configure this route:
以下代碼示範如何配置這種路由: