Click here to Skip to main content
15,881,852 members
Articles / Web Development / ASP.NET

Handling Application Events with HTTP Modules and Logging Application Information

Rate me:
Please Sign up or sign in to vote.
3.36/5 (17 votes)
18 Sep 2007CPOL3 min read 36K   235   25   4
This article describes how to create an HTTP Module that handles application events during the processing of a page request.

Introduction

This article describes how to create an HTTP Module that handles application events during the processing of a page request. The sample module will write information to a log file at various points in the page lifecycle. We will also see how the HTTP Module is configured for use in a sample website.

What is an HTTP Module?

An HTTP Module is a managed component that can respond to events raised by the ASP.NET runtime. The event handler that responds to the Application event can, alternatively, be located in an HTTP Module. The benefit of using an HTTP Module is that it provides a "pluggable" component that can be added to an existing ASP.NET application by simply dropping the HTTP Module assembly in the /bin directory and adding a line or two of configuration to the application's Web.config.

Building an HTTP Module

Here, we use the System.Web.IHttpModule interface in which there are three members defined: two methods and a read-only property that must be implemented. The Init method takes an HttpApplication object, and returns void. The Init method is invoked by ASP.NET to enable a module to handle incoming requests. The Dispose method takes no parameters, and returns void. The Dispose method is invoked by ASP.NET, and is used by the developer for performing any final cleanup work before the ASP.NET Runtime destroys the object. The ModuleName property should return a string containing the friendly name of the module.

Screenshot - httpmodule.jpg

The sample will demonstrate working with both the BeginRequest and EndRequest events of the Application object. When the BeginRequest and EndRequest events are raised, our code will simply write information to a log file. Remember that ASP.NET's HTTP Runtime is not limited to having only one module participating in requests; you could easily have multiple modules acting on each request in both the incoming and outgoing directions. The actual file that is being requested will still be returned to the client. In this case, the file being returned will have information added to the beginning and the end of the stream. This code can be found in LogWriter\LogWriter\LogWriter\LogModule.cs.

C#
(1) namespace LogWriter 
(2)   {
(3)       public class LogModule : IHttpModule
(4)    {
(5)        System.IO.StreamWriter logWriter;
(6)        HttpApplication applicationContext;
(7)        EventHandler beginRequestEventHandler;
(8)        EventHandler endRequestEventHandler;
(9)        String logName;
(10)    public void Init(HttpApplication context)
(11)     {
(12)      //Store file name for later use.
(13)      logName = context.Context.Request.PhysicalApplicationPath + "log.txt";
(14)      //Open file and write information.
(15)      logWriter = new System.IO.StreamWriter(logName, true);
(16)      logWriter.WriteLine("Date :" + 
             System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss"));
(17)      logWriter.WriteLine("Event : Init");
(18)      logWriter.Flush();
(19)      logWriter.Close();
(20)      //Store for access in other events.
(21)      applicationContext = context;
(22)      beginRequestEventHandler = new System.EventHandler(this.OnBeginRequest);
(23)      applicationContext.BeginRequest += beginRequestEventHandler;
(24)      endRequestEventHandler = new System.EventHandler(this.OnEndRequest);
(25)      applicationContext.BeginRequest += endRequestEventHandler;
(26)    }
(27)    public void Dispose()
(28)    {
(29)      //Open file and write information.
(30)      logWriter = new System.IO.StreamWriter(logName, true);
(31)      logWriter.WriteLine("");
(32)      logWriter.WriteLine("Date :" + 
             System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss"));
(33)      logWriter.WriteLine("Event : Dispose");
(34)      logWriter.WriteLine("");
(35)      logWriter.Flush();
(36)      logWriter.Close();
(37)      //Clean-up.
(38)      applicationContext.BeginRequest -= beginRequestEventHandler;
(39)      beginRequestEventHandler = null;
(40)      applicationContext.EndRequest -= beginRequestEventHandler;
(41)      beginRequestEventHandler = null;
(42)    }
(43)    protected void OnBeginRequest(object sender, EventArgs e)
(44)    {
(45)      //Open file and write log information.
(46)      logWriter = new System.IO.StreamWriter(logName, true);
(47)      logWriter.WriteLine("");
(48)      logWriter.WriteLine("Date :" + 
             System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss"));
(49)      logWriter.WriteLine("Event : Application_BeginRequest ");
(50)      logWriter.WriteLine("UserAgent : "  + 
                              applicationContext.Context.Request.UserAgent);
(51)      logWriter.WriteLine("HostAddress : " + 
                              applicationContext.Context.Request.UserHostAddress);
(52)      logWriter.WriteLine("HostName : " + 
                              applicationContext.Context.Request.UserHostName);
(53)      logWriter.WriteLine("SiteURL : " + 
                              applicationContext.Context.Request.Url.ToString());
(54)      logWriter.WriteLine("");
(55)      logWriter.Flush();
(56)      logWriter.Close();
(57)    }
(58)        protected void OnEndRequest(object sender, EventArgs e)
(59)        {
(60)            //Open file and write log information.
(61)            logWriter = new System.IO.StreamWriter(logName, true);
(62)            logWriter.WriteLine("");
(63)            logWriter.WriteLine("Date :" + 
                   System.DateTime.Now.ToString("MM.dd.yyyy HH:mm:ss"));
(64)            logWriter.WriteLine("Event : Application_EndRequest ");
(65)            logWriter.WriteLine("UserAgent : " + 
                                    applicationContext.Context.Request.UserAgent);
(66)            logWriter.WriteLine("HostAddress : " + 
                                    applicationContext.Context.Request.UserHostAddress);
(67)            logWriter.WriteLine("HostName : " + 
                                    applicationContext.Context.Request.UserHostName);
(68)            logWriter.WriteLine("SiteURL : " + 
                                    applicationContext.Context.Request.Url.ToString());
(69)            logWriter.WriteLine("");
(70)            logWriter.Flush();
(71)            logWriter.Close();
(72)        }
(73)    }   
(74) }

A walk-through of the code shows that on line 3, we are creating a class called LogModule that implements the IHttpModule interface. The Init method on line 10, and the Dispose method on line 27, are all required by the IHttpModule interface. The Init method registers two Application event handlers: BeginRequest and EndRequest. Here, we are simply informing the ASP.NET HTTP Runtime that we want to be notified of the application.BeginRequest and application.EndRequest events.

How the HTTP Module is Configured

We need to edit our application's web.config file to include our new IHttpModule. The Web.config file should look like:

XML
<configuration>
  <system.web>
    <httpModules>
      <add type="LogWriter.LogModule" name="LogWriteModule"/>
    </httpModules>
  </system.web>
</configuration>

Conclusion

The article above is basically an introduction to HTTP Handler and HTTP Modules, with a straightforward sample to demonstrate how to handle the application events with an HTTP Module. Using HTTP Handler and HTTP Modules allow your website to be more manageable, extensible, and have less code written in your presentation layer. You encapsulate all the logic inside the HTTP Handler and HTTP Modules. That's all for now. Happy programming !

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Geodis
United States United States
Srinath has done B.Tech from AWH Engineering College ,Calicut , Kerala, India. Currently working in Geodis @ Nashville, USA. He loves to working with Microsoft Technology.

Language / Technology :C#,VB.NET, ASP.NET, AJAX, XML, ADO.Net , WinForms, Javascript, JQuery, PL/SQL, Web Services , SQL Server 2000 & 2005.


Application Server : IIS 5.1, IIS 6.


Certification : IBM Certified Solution Implementer - WebSphere DataPower and MCP Web Client Development


Srinath's Articles:
View My CodeProject Articles





Comments and Discussions

 
QuestionHelp in tracking popup Pin
vijay d4-Jun-09 0:39
vijay d4-Jun-09 0:39 
AnswerRe: Help in tracking popup Pin
Srinath Gopinath22-Jul-09 23:21
Srinath Gopinath22-Jul-09 23:21 
GeneralGood article Pin
sg_cochin28-Nov-07 15:04
sg_cochin28-Nov-07 15:04 
Questionother possible functionality Pin
Thanks for all the fish19-Sep-07 3:11
Thanks for all the fish19-Sep-07 3:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.