Thursday, 29 December 2011

Timing your MVC Actions

Add the following attribute to your MVC actions to view the timing of your mvc actions using System.Diagnostics.Stopwatch class.

This is another filter attribute example.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;

namespace TestActionMethodSelectorAttribute.Attributes
{
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)
{
_stopWatch.Stop();
var response = filterContext.HttpContext.Response;
response.AddHeader("X-elapsed-milliseconds", _stopWatch.ElapsedMilliseconds.ToString());
}
}
}


Usage (homecontroller):


[Stopwatch]
public ActionResult About()
{
return View();
}


It is nice to output the elapsed time in millisecond in the http headers, since we then easily can monitor the values outside Visual Studio, in our browser:


Share this article on LinkedIn.

2 comments:

  1. The reason the About method took over 4000 milliseconds is because I had a breakpoint in my code halting the stopwatch..

    ReplyDelete
  2. I would like to suggest a slight correction in the code. Please add _stopWatch.Reset() before you start and stop the StopWatch This will give accurate results.

    ReplyDelete