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

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

WebAPI3-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方法中的順序來調用的。因此處理器是內嵌的,響應消息以反方向傳遞。即,最后一個處理器首先得到響應消息。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM