computers are cool

mookid on code

My favorite ASP.NET MVC hooks #2: Action filter attributes

June 22nd, 2009 by mookid

Another simple place to hook your stuff in to the framework is action filters. An action filter is an attribute that derives from ActionFilterAttribute which is a convenience class containing the following methods for you to override:

void OnActionExecuting(ActionExecutingContext context);
void OnActionExecuted(ActionExecutedContext context);
void OnResultExecuting(ResultExecutingContext context);
void OnResultExecuted(ResultExecutedContext context);

A lot of the examples around the internet show how to use action filters to restrict access to controller actions or how to apply caching. I won’t do that here, because those concerns are boring. No, we care about how to make life easy for ourselves and how to write testable, non-breakable, maintenance-and-wrist-friendly code. That is, we reserve the right to be lazy.

A fine example on how to be lazy is by letting action filters fetch data for you to avoid repetitive repository gymnastics in every controller action – and I am actually going to be very lazy right now, because I wrote two posts on this topic earlier:

  1. How to avoid duplicate data fecthing with ASP.NET MVC
  2. Another way to avoid duplicate data fetching with ASP.NET MVC

Comments are closed.