Home  >  Article  >  Backend Development  >  What is the usage of DelegatingHandler in Asp.Net webAPI C#?

What is the usage of DelegatingHandler in Asp.Net webAPI C#?

PHPz
PHPzforward
2023-09-12 11:33:04607browse

Asp.Net webAPI C# 中 DelegatingHandler 的用法是什么?

In a message handler, a series of message handlers are chained together. The first handler receives the HTTP request, does some processing, and then hands the request to the next handler. At some point, a response is created and returned to the chain. This pattern is called Delegated Handler.

In addition to the built-in server-side message handlers, we can also create our own server-side HTTP message handlers. Create custom server-side HTTP For message handlers in ASP.NET Web API, we use DelegatingHandler. We have to create a class derived from System.Net.Http.DelegatingHandler. The custom class should then override the SendAsync method.

Task6dd523501409924761d8a0f04c8cbf08 SendAsync(HttpRequestMessage request, CancellationToken CancellationToken);

This method takes HttpRequestMessage as input and returns asynchronously HttpResponseMessage. A typical implementation performs the following operations:

  • Process the request message.
  • Call base.SendAsync to send the request to the internal handler.
  • The internal handler returns a response message. (This step is asynchronous.)
  • Process the response and return it to the caller.

Example

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

Delegate handlers can also skip the inner handler and create the response directly.

Example

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

The above is the detailed content of What is the usage of DelegatingHandler in Asp.Net webAPI C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete