在 Asp.Net webAPI C# 中,DelegatingHandler 的用途是什麼?
在一個訊息處理程式中,一系列訊息處理程式被連結在一起。第一個處理程式接收 HTTP 請求,進行一些處理,並將請求傳遞給下一個處理程式。在某個時刻,響應被建立並回傳到鏈中。這種模式稱為**委託處理程式**。
除了內建的伺服器端訊息處理程式外,我們還可以建立自己的伺服器端 HTTP 訊息處理程式。**要建立自定義伺服器端 HTTP 訊息處理程式**,在 ASP.NET Web API 中,我們使用**DelegatingHandler**。我們必須建立一個從**System.Net.Http.DelegatingHandler**派生的類。然後,該自定義類應該重寫**SendAsync**方法。
Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
該方法以 HttpRequestMessage 作為輸入,並非同步返回 HttpResponseMessage。一個典型的實現執行以下操作:
- 處理請求訊息。
- 呼叫 base.SendAsync 將請求傳送到內部處理程式。
- 內部處理程式返回響應訊息。(此步驟是非同步的。)
- 處理響應並將其返回給呼叫方。
示例
public class CustomMessageHandler : DelegatingHandler{ protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken){ Debug.WriteLine("CustomMessageHandler processing the request"); // Calling the inner handler var response = await base.SendAsync(request, cancellationToken); Debug.WriteLine("CustomMessageHandler processing the response"); return response; } }
委託處理程式還可以跳過內部處理程式並直接建立響應。
示例
public class CustomMessageHandler: DelegatingHandler{ protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken){ // Create the response var response = new HttpResponseMessage(HttpStatusCode.OK){ Content = new StringContent("Skipping the inner handler") }; // TaskCompletionSource creates a task that does not contain a delegate var taskCompletion = new TaskCompletionSource<HttpResponseMessage>(); taskCompletion.SetResult(response); return taskCompletion.Task; } }
廣告