Chapter 11. Action Filters

In the previous chapter, you learned how view components and HTML helpers can encapsulate the rendering of the UI, but they cannot be used to encapsulate the process logic. This can be achieved using action filters.

In this chapter, you learn:

  • What you can use action filters for

  • What kinds of filters are available

  • Which core filters are available inside the framework

  • How to write custom filters

What Is an Action Filter?

An action filter is a custom attribute that you can decorate action methods or controllers with. The framework will then execute the logic inside the action filter before or after the execution of the action method.

You probably already have seen a filter being used. It's in the HomeController that is added by the project template.

[HandleError]
public class HomeController : Controller

By being applied directly to the class definition, the filter is automatically applied to all the actions of the controller. This in particular instructs the ASP.NET MVC framework to handle the errors that might happen inside the actions, using the logic that is defined inside the filter.

If you wanted to handle the errors only for a specific action, you would annotate the method directly:

[HandleError]
public ActionResult Index()

In a typical ASP.NET MVC application, an action is responsible for handling user-initiated requests. The user clicks a button or submits a form, the request is sent and routed through the routing logic to a specific controller, and finally a ...

Get Beginning ASP.NET MVC 1.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.