Created
March 5, 2012 03:49
-
-
Save rbwestmoreland/1976451 to your computer and use it in GitHub Desktop.
Response Time Header IHttpModule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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