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:
Writing a class implementing IHttpModule
Writing handlers for the events you want handled
Subscribing to the events
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
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.
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.
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.
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>");
}
}
}
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() { }
// ...
}
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:
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.