Skip to content

Instantly share code, notes, and snippets.

@gzuri
Created May 8, 2012 21:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gzuri/2639279 to your computer and use it in GitHub Desktop.
Save gzuri/2639279 to your computer and use it in GitHub Desktop.
Provides a basic performance measuring in MVC for each rendered action.
public class StopwatchActionFilter : ActionFilterAttribute
{
private readonly Dictionary<string, Stopwatch> _stopWatches;
public StopwatchActionFilter()
{
if (_stopWatches == null)
_stopWatches = new Dictionary<string, Stopwatch>();
}
public override void OnActionExecuting(ActionExecutingContext filterContext) {
//Gets currently executing action and controller
string actionName = filterContext.RequestContext.RouteData.Values["Action"].ToString();
string controllerName = filterContext.RequestContext.RouteData.Values["Controller"].ToString();
string key = String.Format("NC-{0}-{1}", controllerName, actionName);
if (_stopWatches.ContainsKey(key))
_stopWatches[key].Reset();
else
_stopWatches.Add(key, new Stopwatch());
_stopWatches[key].Start();
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
string actionName = filterContext.RequestContext.RouteData.Values["Action"].ToString();
string controllerName = filterContext.RequestContext.RouteData.Values["Controller"].ToString();
string key = String.Format("NC-{0}-{1}", controllerName, actionName);
if (_stopWatches.ContainsKey(key)){
_stopWatches[key].Stop();
try{
filterContext.HttpContext.Response.AddHeader(key , _stopWatches[key].ElapsedMilliseconds.ToString() + "ms");
}catch{}
}
base.OnActionExecuted(filterContext);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment