Skip to content

Instantly share code, notes, and snippets.

@mahizsas
Forked from dasch/StopwatchAttribute.cs
Last active April 10, 2025 08:15
Show Gist options
  • Save mahizsas/3bb83c05053af8eed147 to your computer and use it in GitHub Desktop.
Save mahizsas/3bb83c05053af8eed147 to your computer and use it in GitHub Desktop.
ASP.NET MVC Stopwatch actionfilterattribute
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