-
-
Save phaniav/c02438d9324ff844442883d301cb556a to your computer and use it in GitHub Desktop.
example of IResultFilter and IActionFilter
This file contains hidden or 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.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