Fals
Fals

Reputation: 6839

HttpMessageHandler vs DelegatingHandler

The DelegatingHandler inherit from HttpMessageHandler. But, I didn't understand the difference, given that you must implement the same method, SendAsync to make both work.

What's the difference between this two Handlers? When should I use each one?

Upvotes: 17

Views: 11915

Answers (2)

Pepito Fernandez
Pepito Fernandez

Reputation: 2440

The difference is very subtle. @Badri gave you a good quick explanation.

Looking at this poster, you realize what it is all about. Keep in mind that when you create your own DelegatingHandlers, you don't mess around with anything that is not specifically HTTP stuff. That's not the place for playing with the BODY in the case of a POST. for example.

One useful thing you can do is to detect very early in the pipe that a token is not present in the headers, then you can terminate right then and there the request and create a StatusCode.Forbidden response. Of course, maybe a simple website doesn't need it. Just an overkill. But if you are receiving millions of calls a minute, it comes very handy since it happens right before the controller is actually instantiated.

There are only a few of cases where you really are going to need that. Or say that the client making the rest call, can only make GET and POST but in the headers it's specifying a X-Method-Override = PUT, then you can at this point modify the request method from POST to PUT, so that your controller/action dispatchers creates the right instance and call the right action.

Here is the interesting poster. PRINT IT :D

http://www.asp.net/media/4071077/aspnet-web-api-poster.pdf

Upvotes: 4

If you are familiar with ASP.NET, then a good analogy will be HTTP handlers and modules. If you implement an HttpMessageHandler, you implement the Send and SendAsync methods and return a response or promise of a response. This is similar to an Http handler. If you implement a DelegatingHandler and add it to the config.MessageHandlers collection, your class runs in the pipeline and gets an opportunity to see and react to the request and responses, just like an HTTP module. DelegatingHandler is also an HttpMessageHandler except that as part of SendAsync implementation, it just calls the SendAsync of the inner handler. The inner handler will do the same and you get the Chinese boxes or the Russian dolls effect. HttpServer, where the pipeline starts is itself a DelegatingHandler.

Upvotes: 23

Related Questions