注:本文是【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所示)。

圖中: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):

圖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。典型的實現要做以下事:
- 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:
以下是一個價值不高的示例:
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 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. 被跳過的處理器
Adding a Handler to the Pipeline
向管線添加一個處理器
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類中做這件事:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MessageHandlers.Add(new MessageHandler1()); config.MessageHandlers.Add(new MessageHandler2());
// Other code not shown(未列出其它代碼)... } }
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框架會自動地連接這些消息處理器。
If you are self-hosting, create an instance of the HttpSelfHostConfiguration class and add the handlers to the MessageHandlers collection.
如果是“自托管”(本系列教程的第8.1小節 — 譯者注)的,需要創建一個HttpSelfHostConfiguration類的實例,並將處事器添加到MessageHandlers集合。
var config = new HttpSelfHostConfiguration("http://localhost"); config.MessageHandlers.Add(new MessageHandler1()); config.MessageHandlers.Add(new MessageHandler2());
Now let's look at some examples of custom message handlers.
現在,讓我們看一些自定義消息處理器的例子。
Example: X-HTTP-Method-Override
示例:X-HTTP-Method-Override
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請求 — 譯者注)。例如:
X-HTTP-Method-Override: PUT
Here is a message handler that adds support for X-HTTP-Method-Override:
以下是添加了X-HTTP-Method-Override支持的一個消息處事器:
public class MethodOverrideHandler : DelegatingHandler { readonly string[] _methods = { "DELETE", "HEAD", "PUT" }; const string _header = "X-HTTP-Method-Override";
protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { // Check for HTTP POST with the X-HTTP-Method-Override header. // 檢查帶有X-HTTP-Method-Override報頭的HTTP POST。 if (request.Method == HttpMethod.Post && request.Headers.Contains(_header)) { // Check if the header value is in our methods list. // 檢查其報頭值是否在我們的方法列表中 var method = request.Headers.GetValues(_header).FirstOrDefault(); if (_methods.Contains(method, StringComparer.InvariantCultureIgnoreCase)) { // Change the request method. // 修改請求方法 request.Method = new HttpMethod(method); } } return base.SendAsync(request, cancellationToken); } }
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會根據這個已被更新的請求方法對該請求進行路由。
Example: Adding a Custom Response Header
示例:添加自定義響應報頭
Here is a message handler that adds a custom header to every response message:
以下是一個把自定義報頭添加到每個響應消息的消息處理器:
// .Net 4.5 public class CustomHeaderHandler : DelegatingHandler { async protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage response = await base.SendAsync(request, cancellationToken); response.Headers.Add("X-Custom-Header", "This is my custom header."); return response; } }
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方法:
public class CustomHeaderHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { return base.SendAsync(request, cancellationToken).ContinueWith( (task) => { HttpResponseMessage response = task.Result; response.Headers.Add("X-Custom-Header", "This is my custom header."); return response; } ); } }
Example: Checking for an API Key
示例:檢查API鍵
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鍵來檢查請求:
public class ApiKeyHandler : DelegatingHandler { public string Key { get; set; }
public ApiKeyHandler(string key) { this.Key = key; }
protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (!ValidateKey(request)) { var response = new HttpResponseMessage(HttpStatusCode.Forbidden); var tsc = new TaskCompletionSource<HttpResponseMessage>(); tsc.SetResult(response); return tsc.Task; } return base.SendAsync(request, cancellationToken); }
private bool ValidateKey(HttpRequestMessage message) { var query = message.RequestUri.ParseQueryString(); string key = query["key"]; return (key == Key); } }
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路由完成之后運行。
Per-Route Message Handlers
單路由消息處理器
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:
另一種辦法是,在定義路由時,對一個特定的路由添加消息處理器:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "Route1", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
config.Routes.MapHttpRoute( name: "Route2", routeTemplate: "api2/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: new MessageHandler2() // per-route message handler(單路由消息處理器) );
config.MessageHandlers.Add(new MessageHandler1()); // global message handler(全局消息處理器) } }
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:
以下代碼演示如何配置這種路由:
// List of delegating handlers. // 委托處理器列表 DelegatingHandler[] handlers = new DelegatingHandler[] { new MessageHandler3() }; // Create a message handler chain with an end-point. // 創建帶有端點的消息處理器鏈 var routeHandlers = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), handlers); config.Routes.MapHttpRoute( name: "Route2", routeTemplate: "api2/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: routeHandlers );
看完此文如果覺得有所收獲,請給個推薦