Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
EPL Standings
Windows XP

Microsoft ASP.NET 4 : HttpModules (part 1) - Existing Modules & Implementing a Module

7/5/2011 3:54:42 PM
Managing global events in Global.asax.cs is a very convenient way to manage data and events in an application. Visual Studio generates a Global.asax.cs and even stubs out the more important events for you. However, using Global.asax.cs isn't the only way to store state and handle application-wide events. The other way is to write an HTTP module.

HTTP modules serve very much the same purpose that Internet Server Application Programming Interface (ISAPI) filters served for classic ASP—as a place to insert functionality in the request processing. HTTP modules plug into the ASP.NET processing chain to handle application-wide events in the same way that Global.asax handles application-wide events. In fact, many ASP.NET features are implemented through HTTP modules. One thing to keep in mind as a caveat before we proceed is that plugging too much into the request chain can start to reduce performance. However, with that in mind modules are a great place to take advantage of the flexibility of ASP.NET.

1. Existing Modules

ASP.NET employs HTTP modules to enable features such as output caching and session state. To get an idea of which features are implemented through HTTP modules, take a look at the master configuration file for your computer (that is, go to the Windows directory, look in the Microsoft.NET directory, and navigate to the configuration directory for the most current release). The master web.config file mentions several modules in the httpModules section of the configuration, as shown in Example 1. For brevity, this list does not include entire strong names of the assemblies, but it gives you an idea of which modules are already part of the ASP.NET pipeline.

Example 1. Excerpt from the master web.config file indicating configured HttpModules
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule"
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
<add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"
<add name="RoleManager" type="System.Web.Security.RoleManagerModule" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
<add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" />
<add name="AnonymousIdentification" type="System.Web.Security.
AnonymousIdentificationModule" />
<add name="Profile" type="System.Web.Profile.ProfileModule" />
<add name="ErrorHandlerModule"
type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="ServiceModel"
type="System.ServiceModel.Activation.HttpModule, System.ServiceModel.Activation,
Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" />
<add name="ScriptModule-4.0"
type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>


The httpModules section mentions the name of a module, followed by a fully specified type that implements the feature. The following features are handled by modules:

  • Output caching

  • Session state

  • Windows authentication

  • Forms authentication

  • Passport authentication

  • Role manager

  • URL authorization

  • File authorization

  • Anonymous identification

  • Profile

  • ErrorHandlerModule

  • ServiceModule-4.0

  • ScriptModule-4.0

The modules fit into the processing chain and take effect prior to being processed by the HttpApplication object. In fact, Microsoft Internet Information Services (IIS) 7.0 uses modules extensively—especially when running in Integrated mode. Although the features themselves can require extensive code to implement (for example, imagine all the work that went into the session state manager), the basic formula for hooking a module into your application is pretty straightforward. Creating a module involves the following four steps:

  1. Writing a class implementing IHttpModule

  2. Writing handlers for the events you want handled

  3. Subscribing to the events

  4. Configuring the module in web.config

2. Implementing a Module

Here's an example illustrating how HTTP modules work. The previous example in this article demonstrates how to time requests by handling events in Global.asax. It shows time stamping the beginning of a request, storing the time stamp in the current HttpContext, and examining the time stamp as the request finishes.

The following example performs the same functionality. However, this example uses an HTTP module to handle the events.

Using a timing module

  1. To implement a timing module, open the Web application solution file for this article—UseApplication. To work, the module needs to exist in an assembly. It's easiest to write a completely separate assembly for the module. Add a project to the solution by clicking File, Add, New Project on the main menu. Make the project a Class Library and name the project TimingModule.

  2. Visual Studio will add a class to the library named Class1. (The name of the file generated by Visual Studio is Class1.cs and the name of the class generated by Visual Studio is Class1.) Change the name of the file to Timer.cs and the name of the class to Timer. Place the code in the TimingModule namespace.

  3. The module as generated by Visual Studio doesn't understand the ASP.NET types. Add a reference to System.Web to make the ASP.NET types available.

  4. Add handlers for the beginning and ending of the request. You can borrow the code from Global.asax if you want. The signatures for the event's handlers are such that the methods have the return type of void and accept two arguments: an object and EventArgs.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;

    /// <summary>
    /// Summary description for Timer
    /// </summary>
    namespace TimingModule {
    public class Timer
    public Timer()
    public void OnBeginRequest(object o, EventArgs ea)
    DateTime dateTimeBeginRequest = DateTime.Now;

    HttpContext ctx;
    ctx = HttpContext.Current;
    ctx.Items["dateTimeBeginRequest"] = dateTimeBeginRequest;

    public void OnEndRequest(object o, EventArgs ea)
    DateTime dateTimeEndRequest = DateTime.Now;

    HttpContext ctx;
    ctx = HttpContext.Current;
    DateTime dateTimeBeginRequest =

    TimeSpan duration = dateTimeEndRequest - dateTimeBeginRequest;

    ctx.Response.Write("<b>From the TimingModule: This request took " +
    duration.ToString() + "</b></br>");

  5. Add IHttpModule to the class's inheritance list. Add implementations for the methods Init and Dispose by right-clicking IHttpModule in the editor and clicking Implement Interface. The job performed by Init is to subscribe to events. The job performed by Dispose is to release any resources used by the module. (Dispose doesn't need to do anything in this example.)

    public class Timer
    : IHttpModule
    public Timer()

    public void Init(HttpApplication httpApp)
    httpApp.BeginRequest +=
    new EventHandler(this.OnBeginRequest);

    httpApp.EndRequest +=
    new EventHandler(this.OnEndRequest);
    public void Dispose() { }

    // ...

  6. The Web site needs to know about the new module. Add a project-level reference (a reference to the new module) to the UseApplication Web application project so that you can use it from the page code. Right-click the UseApplication node in Solution Explorer and click Add Reference. In the Add Reference dialog box, click the Project tab and select TimingModule from the list, and then click OK. The following graphic shows the Add Reference dialog box:

  7. Finally, mention the TimingModule in the web.config file. It needs to appear in the httpModules section, nested within the system.web section, like so:

    <add name="TimingModule"
    type="TimingModule.Timer, TimingModule" />

As long as the TimingModule assembly is available to your application (that is, it's in the Bin subdirectory of your virtual directory), it will be linked into the processing chain. When you run the page, you'll see the timing information coming from both the Global.asax.cs file and the timing module.

Top Search -----------------
- Enabling and Customizing Pen and Touch Features
- Microsoft Visio 2010 : Creating Swimlane Diagrams
- Managing Printing : Deploying Printers Using Group Policy
- Activating and Validating Windows 7
- Managing Disks from the Command Prompt
- Microsoft Excel 2010 : Adding and Deleting a Data Series
- Networking with Windows 7 : Resolving Names to IP Addresses
- Sharing Printers, Scanners, and Fax Machines
- Microsoft Word 2010 : Saving a Document with Macros & Opening a Document with Macros
- Managing Printers Using Print Management (part 2) - Configuring Printer Driver Isolation Mode
Other -----------------
- Microsoft ASP.NET 4 : The HttpApplication Class and HTTP Modules - Overriding HttpApplication
- Microsoft ASP.NET 4 : Diagnostics and Debugging - Error Pages
- Microsoft ASP.NET 4 : Diagnostics and Debugging - Debugging with Visual Studio
- Microsoft ASP.NET 4 : Diagnostics and Debugging - Application Tracing
- Microsoft ASP.NET 4 : Diagnostics and Debugging - Page Tracing
- Microsoft ASP.NET 4 : Caching and State Management - The Wizard Control: An Alternative to Session State
- Microsoft ASP.NET 4 : Caching and State Management - Tracking Session State
- Microsoft ASP.NET 4 : Caching and State Management - Configuring Session State
- Microsoft ASP.NET 4 : Caching and State Management - Session State and More Complex Data
- Microsoft ASP.NET 4 : Caching and State Management - Introduction to Session State
Most view of day
- Windows Server 2008 Server Core : Compressing Data with the Compact Utility
- Manage the Active Directory Domain Services Schema : Remove Attributes from the Index
- Add an InfoPath Form Web Part to a SharePoint Web Part Page
- Microsoft Systems Management Server 2003 : Defining Parent-Child Relationships (part 2) - Installing the Secondary Site Locally from the SMS CD
- Windows Server 2003 : Analyzing Traffic Using Network Monitor (part 1)
- BizTalk 2009 : Host Integration Server 2009 - Planning Your Host Integration Server Topology
- Using Windows Live Programs (part 2) - Using Windows Live Mail
Top 10
- Automating Windows 7 Installation : Customizing Images Using Deployment Image Servicing and Management (part 3) - Servicing the Operating System in an Image , Committing an Image
- Automating Windows 7 Installation : Customizing Images Using Deployment Image Servicing and Management (part 2) - Mounting an Image , Servicing Drivers in an Image
- Automating Windows 7 Installation : Customizing Images Using Deployment Image Servicing and Management (part 1) - Viewing Information about an Image with DISM
- Automating Windows 7 Installation : Applying an Image Using ImageX
- Automating Windows 7 Installation : Capturing an Image Using ImageX
- Microsoft Visio 2010 : Creating Web Pages from Visio Drawings (part 4) - Fine-tuning Web Pages and Battling Bugs - Saving a Visio Drawing as a Web Page
- Microsoft Visio 2010 : Creating Web Pages from Visio Drawings (part 3) - Fine-tuning Web Pages and Battling Bugs - Customizing Web Page Output
- Microsoft Visio 2010 : Creating Web Pages from Visio Drawings (part 2) - Exploring Visio-Generated Web Pages
- Microsoft Visio 2010 : Creating Web Pages from Visio Drawings (part 1) - Saving as Web Page
- Microsoft Visio 2010 : Sending Visio Files in Email, Saving as PDF or XPS Files
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
2015 Camaro