Friday, July 24, 2009 1:40 PM
One of the most efficient and non-intrusive ways you can implement an intercepting procedure is via an HttpModule. An HttpModule simply receives every request going to or coming from IIS and it allows you to manipulate the content as you see fit and pass it along. I wanted to spit out the time it takes from receiving a request to writing the response on one or more web pages and there was no other better way of doing it except writing an HttpModule, it toke me all but 10mins. Here is the code, feel free to blow it up.
class PageLoadTime: System.Web.IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
// nothing to dispose off
}
public void Init(System.Web.HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
context.EndRequest += new EventHandler(context_EndRequest);
}
bool IsReady(System.Web.HttpContext ctx)
{
return (ctx.IsDebuggingEnabled
&& ctx.Request.IsLocal
&& ctx.Response.ContentType.Equals("text/html"));
}
void context_BeginRequest(object sender, EventArgs e)
{
if (IsReady(HttpContext.Current))
{
Stopwatch sw = new Stopwatch();
HttpContext.Current.Items.Add("PageLoadTimeStopWatch", sw);
sw.Start();
}
}
void context_EndRequest(object sender, EventArgs e)
{
if (IsReady(HttpContext.Current))
{
// stop the watch
Stopwatch sw = (Stopwatch)HttpContext.Current.Items["PageLoadTimeStopWatch"];
sw.Stop();
// render the time elapsed
string elapsedTime = string.Format(
"<b>Page Loaded In <font color=red>{0}</font> secs</b>",
decimal.Round(decimal.Parse(sw.Elapsed.TotalSeconds.ToString()), 2));
HttpContext.Current.Response.Write(string.Format("{0}", elapsedTime));
}
}
#endregion
}