ASP.NET MVC has action filters, while ASP.NET has HTTP modules. Inside their respective processing pipelines, these abstractions serve similar purposes, and I've heard the following question a few times:
When should I write an HTTP module and when should I write an action filter?
If you are creating an MVC application then I'll almost always recommend going with an action filter instead of an HTTP module. This is my recommendation even if the functionality you are creating is generic enough to work from inside a module (in other words, it doesn't depend on MVC specific pipeline stages, like the pre and post processing of action invocation). Filters are closely aligned with the MVC infrastructure and vocabulary, and filters are the first thing someone will look for when they want to see how you've implemented cross-cutting functionality in MVC.
On the other hand, an HTTP module is something you can reuse in any type of ASP.NET application. Witness the flexibility of elmah - just drop an assembly in the bin directory, tweak a config file, and wait for elmah to record errors across an entire application. This configurable flexibility isn't something you can do with filters out of the box, but we’ll see tomorrow how easy it is to add.
Comments
If I were advising people, I would say that if the problem you are attempting to solve is Domain Specific to the Application (meaning a knowledge domain, not a .com domain ;-) ), then implement with an Action Filter.
If the problem is generic across possible domains (like ELMAH), then it should be an HTTP Module.
ActionFilters may be executed several times in a single trip to the server (i.e., RedirectToAction, RenderAction, etc.)
They aren't definetly not like HTTP modules.
An HTTP module is called almost every request making HTTP handler (an thus MVC and thus action filters) a more specialized solution for a particular problem.
Sometime ago I named something that almost everyone uses: Page Modules (paulomorgado.net/...). I think this is more close to what action filters are.
I'm working on MVC 3, and I too am inclined to follow "the MVC way" of doing things (i.e. use action filters instead of HTTP Modules). But I ran into the issue of not having a proper interface for implementing a "BeginRequest" filter.
I have this code I need to execute on every request before anything else (even before authentication). I implemented an IFilterProvider, and been playing with both the Order and the FilterScope, but no matter what I try, my authorization filter always kicks in first.
Do you know of a way to create a filter that behaves like BeginRequest does? Thanks!