【ASP.NET Web API教程】5.1 HTTP訊息處理器

來源:互聯網
上載者:User

註:本文是【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。典型的實現要做以下事:

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

看完此文如果覺得有所收穫,請給個推薦

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.