ASP.NET MVC 3: Global action filters

ASP.NET MVC 3 supports global action filters. Global action filters are applied to all actions in web application. By example, you can use global action filters for common security checks. In this posting I will show you how to write dummy action filter, register it as global and test it.

NB! Sample code for this posting is available at my examples GitHub repository as Visual Studio solution.

Creating action filter

Let’s start with our primitive action filter that is able in some cases ruin page layout for IE. Am I evil? Yes, I am! But I want this example to work on IIS and Cassini both so let’s make something trivial.


public class MyActionFilterAttribute : ActionFilterAttribute
{
   
public override void OnResultExecuting(ResultExecutingContext
context)
    {
       
base
.OnResultExecuting(filterContext);

        context.RequestContext.HttpContext.Response.Write(
"<!-- Buuu! -->");
    }
}

All this evil filter does is it writes string <!—Buuu! –> to response stream, so it is the first line of output.

No action filter outputNow open one of your ASP.NET MVC projects and run it. It does not matter if you run it on IIS or Cassini (ASP.NET development web server). If you look at page source you should see usual HTML there. Something like you see on image on right

Registering global action filter

Now, without touching any controller let’s put our evil Buuu! in place. Open global. asax and modify Application_Start event so it looks like follows.


protected void Application_Start()
{
   
AreaRegistration
.RegisterAllAreas();

   
// Register global filter
    GlobalFilters.Filters.Add(new MyActionFilterAttribute
());

    RegisterGlobalFilters(
GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

Compile your project and run application again. Now you should see output like this.

Global action filter output is here

Without any additional modification to controllers and their methods we got our action filter work for all controllers. You can surf around your site and for every request you should see now my evil message.

Conclusion

Global application filters are powerful and easy to use features. You can use global filters for different purposes like establishing global security policies and controlling output. Of course, you may find many other uses for global action filters. ASP.NET MVC makes is very easy to register filters at global level and I think it is another great addition to MVC framework.


One thought on “ASP.NET MVC 3: Global action filters

Leave a Reply

Your email address will not be published. Required fields are marked *