Tuesday, June 26, 2012

ASP.Net MVC: Controllers - Action Filters

Purpose

Used to apply additional logic to Controller Actions without having to directly code that logic in the Action method. Can be applied to Controller class or individual Controller Methods.Cross-cutting logic to your app. Must execute across multiple controller actions but do not want to duplicate that code everywhere.

An Action Filters can be applied globally to all Actions file by registering the filter in global filter list in global.ascx.

Timing

Filter code can be executed at various stages.
  • OnActionExecuting - before method execution
  • OnActionExecuted - after method executing
  • OnResultExecuting - before results are returned to webclient
  • OnResultExecuted - after results are returned to webclient

Built-in Filters

  • AsyncTimeout
  • Authorize - Restrict an action to authorized users or roles. Ensure user is logged in and in the correct role. Can be applied to Controller level as well as action level.
  • ChildActionOnly
  • HandleError - Can specify a view to render in the event of an unhandled exception. Shows friendly page when an error occurs. When error occurs, MVC runtime renders the error view under Views | Shared | Error.cshtml (a normal razor view). Used to process exceptions that might be thrown during action or result execution. Can used for timing actions and logging errors by deriving from HandleErrorAttribute class and overriding the OnException method. In web.config, set <customErrors mode=”RemoteOnly”>   to see the stack trace during development (custom page is show to remote users only)
  • OutputCache - Cache the output of a controller. Cache the result and use for future results.
  • RequireHttps
  • ValidateAntiForgeryToken - Helps prevent cross site request forgeries
  • ValidateInput - Turn off request validation and allow dangerous input.

Custom Filters

You can build and apply your own filters as attributes by implementing a class derived from FilterAttribute or a subclass of FilterAttribute such as ActionFilterAttribute. A global action filter does not need to be derived from any particular base class. An action filter that implements IAuthorizationFilter interface gets executed earlier in the pipeline than other filters.

Applying Filters Globally

Global.asax
RegisterGlobalFilters
filters.Add(new HandleErrorAttribute());