What are built-in message handlers in Asp.Net webAPI C#?


A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class. Message handlers provide us the opportunity to process, edit, or decline an incoming request before it reaches the HttpControllerDispatcher.

Message handlers are executed much earlier in the request processing pipeline, hence they are a great place to implement cross cutting concerns in Web API. Message Handlers are nothing but a chain of classes (it may be system defined or defined by us) that sits next to the process of HTTP request and response through a pipeline.

For example, one HTTP request has come to a HTTP server, now the request will be passed to HandlerA and after processing it in HandlerA, it might go to HandlerB and so on. Now, the advantage here is that we can perform specific tasks within each handler depending on our business needs.

In ASP.NET Web API Framework, there are two types of message handlers are available. They are as follows.

  • Server-Side HTTP Message Handlers
  • Client-Side HTTP Message Handlers

Server-Side Message Handlers

On the server side, the Web API pipeline uses some built-in message handlers −

  • HttpServer gets the request from the host.
  • HttpRoutingDispatcher dispatches the request based on the route.
  • HttpControllerDispatcher sends the request to a Web API controller.

We can add custom handlers to the pipeline. Message handlers are good for crosscutting concerns that operate at the level of HTTP messages (rather than controller actions). For example, a message handler might −

  • Read or modify request headers.
  • Add a response header to responses.
  • Validate requests before they reach the controller.

Client-Side HTTP Message Handlers

On the client side, the HttpClient class uses a message handler to process requests. The default handler is HttpClientHandler, which sends the request over the network and gets the response from the server. We can insert custom message handlers into the client pipeline.

Updated on: 24-Sep-2020

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements