OdeToCode IC Logo

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.