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.
On the server side, the Web API pipeline uses some built-in message handlers −
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 −
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.