Skip to content

Instantly share code, notes, and snippets.

@rbwestmoreland
Created March 5, 2012 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbwestmoreland/1976451 to your computer and use it in GitHub Desktop.
Save rbwestmoreland/1976451 to your computer and use it in GitHub Desktop.
Response Time Header IHttpModule
using System;
using System.Diagnostics;
using System.Web;
public class ResponseTimeHttpModule : IHttpModule
{
private static readonly String XResponseTimeHeaderName = "X-ResponseTime";
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
context.EndRequest += new EventHandler(EndRequest);
}
public void BeginRequest(object sender, EventArgs e)
{
try
{
if (sender is HttpApplication)
{
var httpApplication = (HttpApplication)sender;
var stopwatch = Stopwatch.StartNew();
httpApplication.Context.Items.Add(XResponseTimeHeaderName, stopwatch);
}
}
catch
{
}
}
public void EndRequest(object sender, EventArgs e)
{
try
{
if (sender is HttpApplication)
{
var httpApplication = (HttpApplication)sender;
if (httpApplication.Context.Items.Contains(XResponseTimeHeaderName))
{
var stopwatch = (Stopwatch)httpApplication.Context.Items[XResponseTimeHeaderName];
stopwatch.Stop();
var responseTime = Math.Ceiling(stopwatch.Elapsed.TotalMilliseconds);
var responseTimeString = String.Format("{0} ms", responseTime);
httpApplication.Response.AddHeader(XResponseTimeHeaderName, responseTimeString);
}
}
}
catch
{
}
}
public void Dispose()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment