ASP.NET Web Forms Extensibility: Modules

Next in the series is modules. So, what is a module, and what does it do?

A module is some class that implements IHttpModule. This is a very simple interface, which only defines two methods:

Init: this is the “body” of the module, where you place it’s logic (more on this later), called when the application is started (typically, upon the first request, unless you are doing application initialization);

Out of the box ASP.NET includes a number of modules, which you can find on the global Web.config file, located in %WINDIR%\Microsoft.NET\Framework64\v4.0.30319\Config, some of which you are free to disable, that is, remove on you local Web.config file:

1:<!-- for IIS < 7 -->

2:<httpModules>

3:<removename="PassportAuthentication"/>

4:</httpModules>

5:<!-- for IIS 7+ -->

6:<system.webServer>

7:<modules>

8:<removename="PassportAuthentication"/>

9:</modules>

10:</system.webServer>

11:

As you can see from the above snippet, one such module is PassportAuthentication, implemented by PassportAuthenticationModule, one that is marked as deprecated in current versions of .NET. Now, there are two sections where modules can be registered, one for IIS versions prior to 7, and the other for recent versions. Of course, if you only use one of them, do forget about the other section.

This module registers an event handler for the EndRequest event, which, when called, outputs a string to the response. Nothing to be done on disposing, in this case, but a typical use case would be to release any sort of “heavy” module-held resources when the application shuts down. Please be careful to perform operations only when you can, for example, session is only available after the AcquireRequestState event is raised (and, of course, only for handlers implementing IRequiresSessionState), caller identity is only set after the AuthenticateRequest and authorization is only confirmed after AuthorizeRequest.

You should favor writing code that handles an event in a module as opposed to having a similar method on Global.asax.cs because a module is more portable – you can even reuse it between different assemblies.

Once you are finished, you need to register your module on Web.config, to have it being set up automatically. You have to give it a unique name and add an entry like the following: