Created
May 8, 2012 21:06
-
-
Save gzuri/2639279 to your computer and use it in GitHub Desktop.
Provides a basic performance measuring in MVC for each rendered action.
This file contains 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
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