Filters in ASP.NET MVC.

Filters inject extra logic into MVC Framework request processing. They provide a simple and elegant way to implement cross-cutting concerns. This term refers to functionality that is used all over an application and doesn’t fit neatly into any one place, where it would break the separation of concerns pattern. Classic examples of cross-cutting concerns are logging, authorization, and caching. Filters are .NET attributes that add extra steps to the request processing pipeline.

Types of Filters in ASP.NET MVC and their sequence of execution.

The MVC Framework supports four different types of filters. Each allows you to introduce logic at different points during request processing.

  1. Authorization filters are the filters that are run firstbefore the other kinds of filters and before the action method is invoked. As the name suggests, these filters enforce your authorization policy, ensuring that
    action methods can be invoked only by approved users. Authorization filters implement the IAuthorizationFilter interface. Examples are AuthorizeAttribute and RequireHttpsAttribute.
  2. Exception filters are run only if an unhandled exception has been thrown when invoking an action method. Exception filters must implement the IExceptionFilter interface. For example HandleErrorAttribute.
  3. Action filters are filters that can be used for any purpose. They implement IActionFilter  interface that have two methods OnActionExecuting and OnActionExecuted. The OnActionExecuting method is called before the action method is invoked. You can use this opportunity to inspect the request and select to cancel the request, modify the request, or start some activity that will span the invocation of the action.
  4. Result filters are general-purpose filters which operate on the results produced by action methods. Result filters implement the IResultFilter interface. When we apply a result filter to an action method, the OnResultExecuting method is invoked when the action method has returned an action result but before the action result is executed. The OnResultExecuted method is invoked after the action result is executed.



Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this