
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Usage of DelegatingHandler in ASP.NET Web API
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; } }