StopwatcherAttribute class by Nick Berardi

To take time Nick uses StopwatchAttribute class that you can find from his GitHub repository. I paste this class also here so you can take a look at it without leaving this page. I made some modifications so you can use this class also with ASP.NET development web server.

Now let’s take default controller that is created when you create a new ASP.NET MVC web application.

publicclassHomeController : Controller

{

publicActionResult Index()

{

ViewModel.Message = "Welcome to ASP.NET MVC!";

return View();

}

publicActionResult About()

{

return View();

}

}

We will add nothing to this code by ourselves. We leave it like it is. One thing we have to do is we have to modify our application class in Global.asax.cs.

protectedvoid Application_Start()

{

AreaRegistration.RegisterAllAreas();

GlobalFilters.Filters.Add(newStopwatchAttribute());

RegisterGlobalFilters(GlobalFilters.Filters);

RegisterRoutes(RouteTable.Routes);

}

Okay, now it’s the moment of truth. Let’s see what ASP.NET MVC outputs when we request default page and About page. For both pages you should see something like this in page source.

If you have controller actions that output something other than HTML you cannot write output of StopwatchAttribute class to response – use headers instead of response body.

Conclusion

Global action filters provided by ASP.NET MVC 3 are powerful tools. When working on IIS we can easily make our requests to be easily measured using StopwatchAttribute class when we register it as a global action filter and let it write it’s output to response headers. Tools like Firebug and Fiddler2 allow you to monitor HTTP traffic easily and it is not hard to read headers if you have some of these tools.