Skip to content

Instantly share code, notes, and snippets.

@dasch
Created September 2, 2010 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dasch/562250 to your computer and use it in GitHub Desktop.
Save dasch/562250 to your computer and use it in GitHub Desktop.
using System;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;
/// <summary>
/// A simple attribute that times controller actions, returning the measured time
/// in the HTTP header "X-Duration".
/// </summary>
public class StopwatchAttribute : ActionFilterAttribute
{
private Stopwatch _stopwatch;
public StopwatchAttribute()
{
_stopwatch = new Stopwatch();
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_stopwatch.Start();
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
HttpResponseBase response = filterContext.HttpContext.Response;
_stopwatch.Stop();
response.AppendHeader("X-Duration", string.Format("{0}ms", _stopwatch.ElapsedMilliseconds));
_stopwatch.Reset();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment