Logo
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
PREGNANCY
 
 
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
<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=4.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="ServiceModel"
type="System.ServiceModel.Activation.HttpModule, System.ServiceModel.Activation,
Version=4.0.0.0,
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=4.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</httpModules>


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 =
    (DateTime)ctx.Items["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:

    <configuration>
    <system.web>
    <httpModules>
    <add name="TimingModule"
    type="TimingModule.Timer, TimingModule" />
    </httpModules>
    </system.web>
    </configuration>

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
- Installing and Configuring a Modem : Modifying the Modem’s Advanced Properties
- Installing and Configuring a Modem : Modifying the Modem’s General Properties
- Installing and Configuring a Modem : Working with Different Dialing Locations
- Installing and Configuring a Modem : Installing a Modem & Testing the Modem
- Getting Started with Modem Communications : Modem-to-Modem Communications
- Tuning Windows XP’s Performance : More Optimization Tricks
- Tuning Windows XP’s Performance : Optimizing Virtual Memory
- Tuning Windows XP’s Performance : Optimizing Applications
- Tuning Windows XP’s Performance : Optimizing Startup
- Monitoring Performance with System Monitor
 
 
Most view of day
- SharePoint 2010 and PowerShell: Real-World Solutions : Scripted Installation of SharePoint 2010 Using Windows PowerShell
- SQL Server 2008 R2 : Creating and Managing Stored Procedures - Using Output Parameters, Returning Procedure Status
- System Center Configuration Manager 2007 : Network Design - Troubleshooting Configuration Manager Network Issues (part 2) - Identifying Network Issues Affecting Configuration Manager
- Microsoft Excel 2010 : Inserting Blank Rows (part 1) - Separating Subtotaled Rows for Print
- Microsoft Exchange Server 2007 : Understanding the Client Access Server (part 1) - OWA
- Windows Server 2012 Group Policies and Policy Management : Policy Management Tools (part 1)
- Client Access to Exchange Server 2007 : Using Outlook 2007 Collaboratively (part 2) - Sharing Information with Users Outside the Company
- SQL Server 2012 : Latches and Spinlocks - SuperLatches/Sublatches
- Windows Server 2008 R2 high-availability and recovery features : Installing and Administering Failover Clustering (part 7) - Create shared folder on cluster, Testing Failover of Cluster
- Sharepoint 2013 : Using SkyDrive Pro, Using the timeline feature for tasks, Mentioning a colleague feature
Top 10
- Windows Server 2012 : Administering Active Directory using Windows PowerShell (part 3) - Performing an advanced Active Directory administration task
- Windows Server 2012 : Administering Active Directory using Windows PowerShell (part 2) - Finding Active Directory administration cmdlets
- Windows Server 2012 : Administering Active Directory using Windows PowerShell (part 1) - Managing user accounts with Windows PowerShell
- Windows Server 2012 : Enabling advanced features using ADAC (part 3) - Creating fine-grained password policies
- Windows Server 2012 : Enabling advanced features using ADAC (part 2) - Configuring fine-grained password policies
- Windows Server 2012 : Enabling advanced features using ADAC (part 1) - Enabling and using the Active Directory Recycle Bin
- Microsoft Excel 2010 : Protecting and Securing a Workbook - Marking a Workbook as Read-Only
- Microsoft Excel 2010 : Protecting and Securing a Workbook - Working with Office Safe Modes
- Microsoft Excel 2010 : Protecting and Securing a Workbook - Setting External Content Security Options
- Microsoft Excel 2010 : Protecting and Securing a Workbook - Setting Privacy Options - Set Parental Controls for Online Research
 
 
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
2015 Camaro