December 22, 2014
Hot Topics:

Intercepting Every HTTP Request with IHttpModule

  • April 20, 2009
  • By Paul Kimmel
  • Send Email »
  • More Articles »

Introduction

The Global.asax file contains the Global Application Class that is the object representation of your running web application. You can use the Global Application Class to handle application events like Start, End, and Error, and user session events like Start and End. The Global Application Class is a great place to do things like cache application data for performance improvements and handle exceptions that slip by everything else.

You can use the Global Application Class for application-level and session-level events or you can implement a re-deployable solution as an IHttpModule, which can be added directly to your Web application or as a separate class library. An IHttpModule is registered in the Web.Config file and it is notified of every HTTP request. How your IHttpModule responds depends on how you code it.

To demonstrate the IHttpModule, this article presents a straight forward implementation that tracks the IP address and date and time of every request. These requests are sent to the console in the example, but you could easily track the requests in cache, display them on a web page, or store them in a database.

Implementing IHttpModule

IHttpModule is an interface defined in System.Web.dll. The interface contains only two method signatures: Init and Dispose. On the Init method wire up, the behavior—for example application events—that you want the IHttpModule to support and perform any clean up in the Dispose method.

The Init method receives an instance of the application object (HttpApplication). The easiest way to tap into application behaviors is to wire an event handler to application-level events. The example module listens to application BeginRequest events and sends the requestor information along with the date and time to the Debug output window (the Immediate window by default). Check out Listing 1 for an implementation of IHttpModule.

Listing 1: Implement the IHttpModule to listen in on every single HTTP request.

Imports Microsoft.VisualBasic
Imports System.Diagnostics
 
Public Class MyHttpModule
  Implements IHttpModule
 
 
  Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
 
  End Sub
 
  Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
    AddHandler context.BeginRequest, AddressOf BeginRequest
  End Sub
 
  Protected Sub BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    BeginRequest(DirectCast(sender, HttpApplication))
  End Sub
 
  Protected Sub BeginRequest(ByVal application As HttpApplication)
    Dim mask As String = "{0} last accessed the site at {1}"
    Try
      Debug.WriteLine(String.Format(mask, application.Request.UserHostAddress, DateTime.Now))
    Catch ex As Exception
    End Try
  End Sub
 
End Class

In Listing 1 it is assumed that you will add the new class to the App_Code folder. (For re-deployment purposes you can create a separate class library for the IHttpModule.) In the listing the Init method associates an event handler with the HttpApplication.BeginRequest event. When that event occurs the BeginRequest method, which is overloaded, uses the application object to write out the UserHostAddress.

To get an application to use the IHttpModule you will need to register it in the Web.config file.

Registering the HTTP Module

IHttpModules are registerd in the <httpModules> section of the Web.Config file. Listing 2 shows a complete sample Web.Config with MyHttpModule highlighted with a bold font. (Boilerplate elements were taken out by me to shorten the Web.Config file.)

Listing 2: The Web.Config showing the placement and introduciton of the IHttpModule from Listing 1.

 
<?xml version="1.0"?>
<configuration>
  <configSections>
    
  </configSections>
  <appSettings/>
  <connectionStrings/>
  <system.web>
    
    <compilation debug="true" strict="false" explicit="true">
    <authentication mode="Windows"/>
    <httpHandlers>
    
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, 
           System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
           PublicKeyToken=31BF3856AD364E35"/>
        <add name="MyHttpModule" type="MyHttpModule"/>
    </httpModules>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
                type="Microsoft.CSharp.CSharpCodeProvider, System, 
                Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" 
                warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, 
                System, Version=2.0.0.0, Culture=neutral, 
                PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="OptionInfer" value="true"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
    <handlers>
  </system.webServer>
  <runtime>
  </runtime>
</configuration>

To use MyHttpModule successfully just add the tag shown below to the <httpModules> section. The more complete listing in Listing 2 was shown to give you an idea where to find the <httpModules> section.

<add name="MyHttpModule" type="MyHttpModule"/>

Summary

There are two general kinds of ways that HTTP messages are sent from your customer's client computers and the web server: postback and callback. The postback is the synchronous traditional way of sending data to the server and usually happens through basic interactions like button clicks. The callback is currently associated with Ajax behavior. The lifecycle for a web page differs between postbacks and callbacks. One way to ensure that behaviors that have to happen regardless of how data is sent to and requested from your server is to use the Global Application Class and another way is to implement an IHttpModule. If you need an easily re-deployable HTTP handler then implement the IHttpModule in a Class Library.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his upcoming book LINQ Unleashed for C# now available on Amazon.com and fine bookstores everywhere. Look for his upcoming book Teach Yourself the ADO.NET Entity Framework in 24 Hours. You may contact him for technology questions at pkimmel@softconcepts.com. Paul Kimmel is a Technical Evangelist for Developer Express, Inc, and you can ask him about Developer Express at paulk@devexpress.com and read his DX blog at http://community.devexpress.com/blogs/paulk.


Tags: ASP.NET, Visual Basic, Microsoft, Web




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel