Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
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.

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
Top 10 video Game
-   Minecraft Mods - MAD PACK #10 'NETHER DOOM!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #9 'KING SLIME!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #2 'LAVA LOBBERS!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Minecraft Mods - MAD PACK #3 'OBSIDIAN LONGSWORD!' with Vikkstar & Pete (Minecraft Mod - Mad Pack 2)
-   Total War: Warhammer [PC] Demigryph Trailer
-   Minecraft | MINIONS MOVIE MOD! (Despicable Me, Minions Movie)
-   Minecraft | Crazy Craft 3.0 - Ep 3! "TITANS ATTACK"
-   Minecraft | Crazy Craft 3.0 - Ep 2! "THIEVING FROM THE CRAZIES"
-   Minecraft | MORPH HIDE AND SEEK - Minions Despicable Me Mod
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 92 "IS JOE DEAD?!"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 93 "JEDI STRIKE BACK"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 94 "TATOOINE PLANET DESTRUCTION"
-   Minecraft | Dream Craft - Star Wars Modded Survival Ep 95 "TATOOINE CAPTIVES"
-   Hitman [PS4/XOne/PC] Alpha Gameplay Trailer
-   Satellite Reign [PC] Release Date Trailer
Popular tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 windows Phone 7 windows Phone 8
programming4us programming4us
Popular keywords
HOW TO Swimlane in Visio Visio sort key Pen and Touch Creating groups in Windows Server Raid in Windows Server Exchange 2010 maintenance Exchange server mail enabled groups Debugging Tools Collaborating
programming4us programming4us
PS4 game trailer XBox One game trailer
WiiU game trailer 3ds game trailer
Trailer game
Natural Miscarriage
Windows Vista
Windows 7
Windows Azure
Windows Server
Game Trailer