i have been searching online for examples of how to create an HttpModule, since i wanted to use one in a website i am developing atm. all the examples i have found were pretty simple looking, but harder to implement then i though in the begining.
here is a sample HttpModule:
public class SampleModule : IHttpModule
{
DateTime beginrequest;
public void Init(HttpApplication app)
{
// register for events created by the pipeline
app.BeginRequest += new EventHandler(this.OnBeginRequest);
app.EndRequest += new EventHandler(this.OnEndRequest);
}
public void Dispose() { }
public void OnBeginRequest(object o, EventArgs args)
{
// obtain the time of the current request
beginrequest = DateTime.Now;
}
public void OnEndRequest(object o, EventArgs args)
{
// get the time elapsed for the request
TimeSpan elapsedtime = DateTime.Now - beginrequest;
// get access to application object and the context object
HttpApplication app = (HttpApplication)o;
HttpContext ctx = app.Context;
// add header to HTTP response
ctx.Response.AppendHeader("ElapsedTime", elapsedtime.ToString());
}
}
implementing the module should have been like so (by all the examples i have found):
<configuration>
<system.web>
<httpModules>
<add name="TimeElapsedModule" type="SampleModules.SampleModule,SampleModules "/>
</httpModules>
</system.web>
</configuration>
but this isnt right for IIS7! in IIS7 you should do:
<system.webServer>
<modules>
<add name="TimeElapsedModule" type="SampleModules.SampleModule,SampleModules"/>
</modules>
</system.webServer>
now, after figuring that out, i encountered another problem which i dont seem to find a solution for. i am getting the following error:
Could not load file or assembly 'SampleModules' or one of its dependencies. The system cannot find the file specified.
which is logical, since my module lives inside another class. i would be happy if someone could help me solve this issue and i am hoping this post will help fellow programers on their day of need.
Turns out for the type I was using the namespace instead of the class name qualified with the namespace. In other words in my web.config I had
<add type="SampleModules.SampleModule,SampleModules" name="TimeElapsedModule" />
instead of
<add type="Test.SampleModules.SampleModule,App_Code" name="TimeElapsedModule" />