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

CsharpServer Side ProgrammingProgramming

In a message handler, 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.

Along with the built-in Server-side Message Handlers, we can also create our own Server-Side HTTP Message Handlers. To create a custom Server-Side HTTP Message Handler in ASP.NET Web API, we make use of DelegatingHandler. We have to create a class deriving from System.Net.Http.DelegatingHandler. That custom class then should override the SendAsync method.

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 −

  • Process the request message.
  • Call base.SendAsync to send the request to the inner handler.
  • The inner 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;
   }
}

A delegating handler can also skip the inner handler and directly create the response.

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;
   }
}
raja
Published on 24-Sep-2020 15:10:53
Advertisements