Royi Namir Royi Namir - 1 month ago 10
ASP.NET (C#) Question

Message Handlers and the Http Module?

In ASP.NET Web API, HTTP requests and responses are processed in a
pipeline on the server.

If I want to add some logic or global behaviour at the very early stages of the pipeline , I should do it in the Message Handler. ( for example : authentication)

But what about the Http module pipeline ? where it fits in this whole story ?

Looking at this numbered stages of web api life cycle :

enter image description here

But looking at the Http module general events ( contains more but...) enter image description here

Question :

— How those 2 systems combine and where ? I mean if there was 1 picture which contains web api and http module , how would the numbers be ? (I added numbers in the images for easy referencing)

— I always hear that If i want to do things earlier at the pipeline I should use message handlers , but what about HttpModule's
for example ? I know that there are objects which are null at this stage but still , later phases at the httpmodule does inflate HttpContetxt's objects - and yet , webapi's guys says : use MessageHandlers....(is it relate to the fact of selfhoster environment) ?


To combine the figure below into the top one, imagine IHttpHandler box in the top figure corresponds to ASPX in the below image so that you put the down image to the bottom left of the top one. So, 8 and 9 are part of the IIS ASP.NET pipeline. IIS pipeline runs modules, etc and terminates when a handler handles the request. With web API, that handler happens to be HttpControllerHandler and this is where Web API pipeline starts. If you look at HttpControllerHandler, the request and response are ASP.NET specific to its left and to its right it becomes HttpRequestMesssage which is Web API specific.

To your second question, the earliest you could do in Web API pipeline will be a message handler. HttpModule will be even more earlier but is not part of Web API but the hosting. Trade-off is that if you have an HttpModule, you can use it only in IIS whereas a message handler can run in any host, since it is Web API specific and host-specific. I keep referring to my MSDN article in my recent SO replies but then it so happens that the article is relevant to the questions being asked. So, I have no other go but to again link it. Here you go. I have comparison of different options in that article.