-
-
Save mahizsas/3bb83c05053af8eed147 to your computer and use it in GitHub Desktop.
ASP.NET MVC Stopwatch actionfilterattribute
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
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