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…