ActionFilter Overkill

Thursday, July 1, 2010

We've seen not one, but two posts this week where we used an ActionFilter as the solution to a problem. ActionFilters are powerful. ActionFilters can inspect and modify action parameters and action results. They can cover almost any cross-cutting concern in ASP.NET MVC: caching, security, auditing, etc.

But, should you use them everywhere?

[Log, UnitOfWork, PreParseParams]
[CommonData, VerifyRedirects, HandleError]  
public class BusyController : Controller
{
    
}

Think about the other options:

HttpModules see the big picture. They can hook into the beginning of a request before a request even knows it's destined for a controller. Modules are configurable at runtime and can drop into any web site as a completely decoupled component (example: ELMAH).

Custom ModelBinders can build and tweak models, build action parameters, and provide some validation support. I'd use a model binder instead of an action filter if I wanted to change or inspect model or parameter values (see: tips for model binding).

Custom ActionResults can encapsulate what happens after an action finishes executing. Modify HTTP headers, set response properties, and more (example: custom ImageResult).

Don't default to using an ActionFilter if another solution is a better fit.


Comments
gravatar Jake Scott Friday, July 2, 2010
The MvcExtensions project on codeplex has a fluent api for registering action filters http://mvcextensions.codeplex.com/

weblogs.asp.net/...
gravatar Scott Friday, July 2, 2010
@Jake - it's not as much as issue of how to register the action filters - it's more about using action filters in places where a model binder or custom action result might be appropriate.
gravatar Surge Saturday, July 3, 2010
good info thanks
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!