Action Filters

Sponsored Links

ASP.NET MVC Action Filters

Here we look at the ASP.NET MVC Action Filters.

Action Filters are attributes which can be applied to an action method or a whole controller. They allow for both pre and post action method execution, such that the filters can run before or after the action method has run.

There are 4 types (as of .NET 4.0) of ActionFilter:


Action Filters applied to an Action Method are applied in the order shown above, should there be more than one filter applied.

The Authorisation type of ActionFilter deals with security decisions, and can prevent an action method from running should security fail. This provides security to stop views being rendered when the user isn't authorised. The Action filter wraps the action method to provide an outer layer to the method. The Result filter wraps the execution of the ActionResult which allows control of the response of the HTTP response. The Execution filter allows particular error handling to be performed with the action method.


So you can use the [Authorize] attribute to stop an action method from being run by a user who doesn't have authentication, or even apply the attribute to the whole Controller class to stop any of the Controller class from executing when the user doesn't have access.

public ActionResult ChangePassword()


You can use the [OutputCache] attribute to mark that the output of a method is cached. The following example marks that the resulting String will be cached for 10 seconds. If we applied this attribute to the controller, all methods in that controller would be cached.

[OutputCache(Duration=10, VaryByParam="")]
public String ThisTime()
    return DateTime.Now.ToString("T");


You can use the [HandleError] attribute on your action methods as a means of error handling. The default setting is to send users to the Views/Shared/Error view, though you can use multiple [HandleError] attributes to target specific Exceptions.

public class HomeController : Controller