Friday, May 8, 2009

HTTP Modules Versus Global.asax Files

You can implement much of the functionality of a module in the application's Global.asax file, which enables you to respond to application events. However, modules have an advantage over the Global.asax file because they are encapsulated and can be created one time and used in many different applications. By adding them to the global assembly cache and registering them in the Machine.config file, you can reuse them across applications. For more information, see Global Assembly Cache.

The advantage of using the Global.asax file is that you can handle other registered events such as Session_Start and Session_End. In addition, the Global.asax file enables you to instantiate global objects that are available throughout the application.
You should use a module whenever you must create code that depends on application events, and when the following conditions are true:
# You want to re-use the module in other applications.
# You want to avoid putting complex code in the Global.asax file.
# The module applies to all requests in the pipeline (IIS 7.0 Integrated mode only).
You should add code in the Global.asax file whenever you must create code that depends on application events and you do not have to reuse it across applications. You can also use the Global.asax file when you have to subscribe to events that are not available to modules, such as Session_Start.

Global.asax file is derived from HttpApplication class and it does not implement IHttpModule interface like custom modules. If you are not going to use your custom module in any other application or don’t have complex logic than you should use Global.asax instead of creating custom modules.
You can have multiple modules in your web application implementing same events. Modules are called in the sequence they are added in the web.config file. With in a module events are called in following sequence:


Event calling sequence in multi module Scenario:
Suppose there are Global.asax and 2 custom modules namely Module.cs and Module1.cs in an application. Custom modules are added in web.config in following order.

< httpModules >
< add name="MyModule1" type="MyModule1" />
< add name="MyModule" type="MyModule" />
< /httpModules >

And all of them are handling first 3 event in the above given list – BeginRequest , AuthenticateRequest, AuthorizeRequest.

The sequence of event call will be as follows:

Application_Start - Global.asax
Init - Global.asax
BeginRequest - MyModule1
BeginRequest - MyModule
BeginRequest - Global.asax
AuthenticateRequest - MyModule1
AuthenticateRequest - MyModule
AuthenticateRequest - Global.asax
AuthorizeRequest - MyModule1
AuthorizeRequest - MyModule
AuthorizeRequest - Global.asax
Session_Start - Global.asax

1 comment: