Skip to content

Instantly share code, notes, and snippets.

@amokan
Created July 15, 2011 19:37
Show Gist options
  • Save amokan/1085387 to your computer and use it in GitHub Desktop.
Save amokan/1085387 to your computer and use it in GitHub Desktop.
example of IResultFilter and IActionFilter
using System.Diagnostics;
using System.Web.Mvc;
namespace YourApp.Web.Infrastructure.Filters
{
/// <summary>
/// Filter to display the execution time of both the action and result
/// </summary>
public class RequestTimingFilter : IActionFilter, IResultFilter
{
private static Stopwatch GetTimer(ControllerContext context, string name)
{
var key = string.Format("__timer__{0}", name);
if (context.HttpContext.Items.Contains(key))
{
return (Stopwatch)context.HttpContext.Items[key];
}
var result = new Stopwatch();
context.HttpContext.Items[key] = result;
return result;
}
/// <summary>
/// Called before an action method executes.
/// </summary>
/// <param name = "filterContext">The filter context.</param>
public void OnActionExecuting(ActionExecutingContext filterContext)
{
GetTimer(filterContext, "action").Start();
}
/// <summary>
/// Called after the action method executes.
/// </summary>
/// <param name = "filterContext">The filter context.</param>
public void OnActionExecuted(ActionExecutedContext filterContext)
{
GetTimer(filterContext, "action").Stop();
}
/// <summary>
/// Called before an action result executes.
/// </summary>
/// <param name = "filterContext">The filter context.</param>
public void OnResultExecuting(ResultExecutingContext filterContext)
{
GetTimer(filterContext, "render").Start();
}
/// <summary>
/// Called after an action result executes.
/// </summary>
/// <param name = "filterContext">The filter context.</param>
public void OnResultExecuted(ResultExecutedContext filterContext)
{
var renderTimer = GetTimer(filterContext, "render");
renderTimer.Stop();
var actionTimer = GetTimer(filterContext, "action");
var response = filterContext.HttpContext.Response;
if (response.ContentType == "text/html")
{
response.Write(
string.Format(
"<div style='font-size: 70%; font-weight: bold; color: #888;'>Action '{0} :: {1}'<br /> Execute: {2}ms, Render: {3}ms.</div>",
filterContext.RouteData.Values["controller"],
filterContext.RouteData.Values["action"],
actionTimer.ElapsedMilliseconds,
renderTimer.ElapsedMilliseconds
)
);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment