HTTP Message Handler in ASP.Net Web API

Introduction

This article defines the message handler that handles requests and responses.

Message Handler

This class is inherited from the HttpMessageHandler class. The message handler receives the request and returns the response. There is a chain of the message handlers. This chain is known as the delegating handler. The request is received by one handler for performing some process and then passed to the other handler. The chain performs the processing and at last the response is sent back along the chain.

msg.jpg

Server Side Message Handler

There are some message handlers that are work on server side; they are:

  • HttpServer: The HttpServer receives the request from the host.
  • HttpRouting dispatcher: The request is dispatched by it according to the route.
  • HttpControllerDispatcher: It transfers the request to the Web API controller.

The Message Handler might perform as in the following:

  • It can read the request and perform any type of modification.
  • It can add the response to the response header.
  • Before transferring the request to the something, it is validated by the message handler.

We can also add a custom handler. The message handler handles the level of the messages. The following diagram shows inserting the custom controller.

msg1.jpg

Custom message handler

For adding the controller we need the class "System.Net.Http.DelegatingHandler" from which the controller is derived and the method SendAsync. The following is the signature of the method.

 

  1. Task<HttpResponseMessage> SendAsync(  
  2.     HttpRequestMessage req, CancellationToken can);  

 

This method receives the request that is HttpRequestMessage as input and returns the response that is HttpResponseMessage. The following is what is done by the method:

  • First it processes the request message.
  • Then it calls the SendAsync method to send the request to the handler.
  • Then the handler returns the response.
  • The response process is done and is sent back to the host.
msg2.jpg

Adding the controller:

For adding the message handler, first we need to add the handler to the collection HttpConfiguratioh.MessageHandler. If added to the controller of the ASP.NET MVC 4 application project then you can do it inside the WebApiConfig class.

  1. public static class WebApiConfig  
  2. {  
  3.     public static void Register(HttpConfiguration config)  
  4.     {  
  5.         config.MessageHandlers.Add(new MessageHandler1());  
  6.         config.MessageHandlers.Add(new MessageHandler2());  
  7.     }  
  8. }