Fluent-API to add ActionFilters to Controllers – ASP.NET MVC Part 3

The latest source code for my Fluent-API to add Action Filters to Controllers is no available here. If you haven’t read about my test project, you can find the other posts here:

Fluent-API to add ActionFilters to Controller in ASP.NET MVC

Fluent-API to add ActionFilters to Controllers – ASP.NET MVC Part 2

To use the Fluent-API, you only need to change the Default Controller factory to the ActionFilterConfigControllerFactory, then just configure your controller within the Global.asax. Here is an example where the OutputCache is added to two Action methods, and also an example how to add one or many ActionFilters to one Action method. You can also add Action Filters on a Controller level so they will be used on every Action methods. If you also want a specific Action Filter for all Controllers, you can just Configure the Controller type and add the filters to it.

protected void Application_Start()


private void RegisterActionFilters()
            // Add OutputCache to all Action Methods for all Controllers which inherits the Contoller class
            //  .AddFilterToController(new OutputCacheAttribute() { Duration = 10, VaryByParam = "none" });

                            .AddFilterToController(new HandleErrorAttribute())
                            .AddFilterToActions(new OutputCacheAttribute() { Duration = 10, VaryByParam = "none" },
                                                c => c.About(),
                                                c => c.Index());

                              .AddFilterToAction(c => c.LogOn(), 
new HandleErrorAttribute(),
new MyCustomFilterAttribute()); }

This is as I wrote only a test project, and I do like the idea to add cross-cutting concerns by not adding attributes directly to the Controllers source code.

No Comments