Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

MVC Action Filter

Options
  • 07-03-2013 11:36am
    #1
    Registered Users Posts: 442 ✭✭


    Hi,
    Can anyone explain in simple terms what an mvc action filter is, and how it works?

    Thanks


Comments

  • Registered Users Posts: 2,021 ✭✭✭ChRoMe




  • Registered Users Posts: 11,979 ✭✭✭✭Giblet


    An action filter is used to intercept events in the lifetime of an action called on a controller.
    They can be applied per action, globally, or to a specific controller (and other ways through reflection)

    The four main events that can be intercepted or overridden are

    OnActionExecuting: Which allows access to the ActionExecutingContext, which allows you to run code that executes before the action is run, and it allows you access to the controller, the view data, and the parent view data is applicable.

    OnActionExecuted: Similar to the above, except it triggers after the action has executed but before the view has rendered, you can read and alter the model here.

    OnResultExecuting: This runs before the view is rendered, has access to the result, and you can apply filters here for rendering.

    OnResultExecuted: Runs after the view, can override the written HTML stream, if buffered and not sent, check exceptions that have occurred.

    It's useful for moving boilerplate code used in every controller into the infrastructure layer. (IE: Session and Transaction Management in an ORM).


  • Registered Users Posts: 1,311 ✭✭✭Procasinator


    Yeah, Google will probably do.

    In simple terms, allows you to run code before/after an action (or result) is called.

    So, you might use the AuthorizeAttribute to cancel calling the action unless the user has permission, maybe redirecting to a login page.

    Or you might use the OutputCacheAttribute that caches action results. So when OnActionExecuting it can check if a valid entry is in the cache, and if so, return the result straight away instead of calling the Action. Otherwise, it can let the process unfold and cache the result for future calls.


Advertisement