mvc - questions - HTTP module vs action filter in

iactionfilter (2)

  1. Filter are more MVC approach of doing thing whereas Http Module are more of ASP.NET way of doing thing. Both serve similar purpose by providing hook in the processing pipline.

  2. HttpModule is more generic and when you want some thing to be processed on every request. Filters are useful for adding action specific behaviour.

  3. If you want some thing to be executed only once per Http Request, you should use an HttpModule. ActionFilter may get executed several times during a request until and unless you check IsChildActionOn.

I am developing an application in MVC3 and I have the following questions: When should I write an HTTP module and when should I write an action filter?

HttpModule is how IIS allows an Web application to override the default behavior or add custom logic by letting you attach event handlers to HttpApplication events. Different IIS modes (Integrated or Classic) even use has different Web.config settings.

Example: redirect non-www to www URLs

public void Init(HttpApplication application)
    application.PreRequestHandlerExecute += this.Application_PreRequestHandlerExecute;

private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    Uri requestUrl = HttpContext.Current.Request.Url;
    string host = requestUrl.Authority.ToLower();
    if (!host.StartsWith("www"))
        HttpContext.Current.Response.Redirect(requestUrl.Scheme + "://www." + host + requestUrl.PathAndQuery);

An Action Filter is an attribute decorating controllers or action methods. It is an abstraction layer between MVC routing and action methods. With action filters, we can apply same logic to multiple controllers or action methods. for example, custom logging.