在 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;
   }
}

更新于: 2020-09-24

4K+ 次查看

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.