OdeToCode IC Logo

Global.asax or an HttpModule?

Thursday, February 3, 2005

We know HttpApplication events like BeginRequest, AuthorizeRequest, and Error can be extremely useful for implementing functionality like URL re-writing and custom authentication schemes. We can choose to catch these events in one of two places: inside of the methods provided by Global.asax, or inside a custom HttpModule.

I favor the global.asax approach only if the logic inside the events is heavily application specific. In general, an HttpModule is the best approach for a number of reasons.

Firstly, I don’t want global.asax to become a dumping ground for code snippets that need to execute during the request lifetime. Using one or more HttpModules allows me to cleanly factor out responsibilities into distinct classes. A clean design also allows me to place the HttpModule in a class library for reuse across multiple projects.

Secondly, HttpModules are a bit more flexible since I can add them and remove them at runtime with a modification to web.config (or machine.config). A testament to the flexibility and power of an HttpModule is the ValidatePathModule released by Microsoft last year to avoid canonicalization bugs in ASP.NET (note to self: make sure the spell checker doesn’t replace canonicalization with cannibalization). Looking far down the road to the Longhorn timeframe, HttpModules will have even more flexibility in the componentized .NET-aware IIS 7.0. More details on new features in IIS 7.0 next week…

Milan Negovan Thursday, February 3, 2005
I favor HttpModules too. I like their pluggable architecture and separation of duties.
<br>I also like it that I can wire an HTTP pipeline event without guessing how to deduce its name (is it &quot;Session_Start&quot; or Session_OnStart&quot;). Populating Global.asax feels like the ol' ASP days (*shivers down the spine*). Besides, the Session_End event has been a target of way too much confusion. I wish it didn't exist in the first place.
<br>Sometimes it's beneficial to rip a Global.asax out completely. If you don't use any session state, chances are you don't need Global.asax.
<br>As long as global.asax is present, the runtime uses it to compile a class derived from HttpApplication and has it process a request. Again, if you don't use any session or application state, it's a waste.
Luca Minudel aka (luKa) Wednesday, November 23, 2005
IMHO the central point in favor of httpmodules came when you have a portal with many distinct web applications.

You can attach the same httpmodule to all web apps just using web.config inheritance and keep functions implemented in httpmodule decoupled from the web apps. With Globa.asax this cannot be done.

ciao (luKa)
Comments are closed.