Understanding Action Filters in ASP.NET MVC

Introduction

To understand MVC Action Filters, we have to know how ASP.NET MVC routing works. When a user types an ASP.NET MVC application URL in the browser, it lands at the UrlRoutingModule. The routing module parses the requested URL and then invokes the corresponding controller and action. Finally, the controller renders the appropriate view and the response is sent to the user. Now assume, a developer wants to inject some additional processing logic which could be reused across multiple controllers and actions in the request response life cycle. MVC custom filters allow developers to inject additional processing logic in the request-response life cycle.

Action filter attributes can be applied to an individual action method or to a controller. When applied to a controller, it will be applicable to all the action methods written for that controller.

When to Use MVC Filters

Developers can use an MVC filter to perform certain actions before or after a particular operation or during a pre- or post-action behavior from the action. MVC filters are used to perform common functionalities in an ASP.NET MVC application, such as custom authentication and authorization, error handling or logging, user activity logging, data caching, and data compression.

Types of Filters

There are five types of Filters in ASP.NET MVC 5.0:

  • Authentication Filters (available in ASP.NET MVC5)
  • Authorization Filters
  • Action Filters
  • Result Filters
  • Exception Filters

Examples of ASP.NET MVC Filters

Authentication Filters

Introduced with ASP.NET MVC5, an authentication filter is a component that authenticates an HTTP request. Both Web API 2 and MVC 5 support authentication filters. The IAuthenticationFilter interface is used to create CustomAuthentication filter. Refer the following code snippet.

namespace MVCFilters
{
   public interface IAuthenticationFilter
   {
      void OnAuthentication(AuthenticationContext
         AuthenticationFilterContext);

      void OnAuthenticationChallenge(AuthenticationChallengeContext
         filterContext);
   }

   public class CustomAuthenticationAttribute :
         ActionFilterAttribute, IAuthenticationFilter
   {
      public void OnAuthentication(AuthenticationContext
         filterContext)
      {
         // Custom logic for user authentication
      }

      public void OnAuthenticationChallenge
         (AuthenticationChallengeContext filterContext)
      {
         // Any Additional tasks on the request

      }
   }
}

Authorization Filters

Authorization filters are required to provide an authorization level in the application. The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. Also, the AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.

The following snippet shows how the Interface and the class operate.

namespace MVCFilters
{
   public interface IAuthorizationFilter
   {
      void OnAuthorization(AuthorizationContext filterCOntext);
   }

   public class AuthorizeAttribute : FilterAttribute,
      IAuthorizationFilter
   {
      protected virtual bool AuthorizeCore(HttpContextBase
         httpContext);
      protected virtual void HandleUnauthorizedRequest
         (AuthorizationContext filterContext);
      public virtual void OnAuthorization(AuthorizationContext
         filterContext);
      protected virtual HttpValidationStatus OnCacheAuthorization
         (HttpContextBase httpContext);
   }

}

Action Filters

Action filters are used to implement the logic that get executed before or after a controller action executes. The IActionFilter interface is used to create an Action Filter. That interface provides two methods: OnActionExecuting and OnActionExecuted. These methods will be executed before or after an action is executed, respectively.

namespace MVCFilters
{
   public interface IActionFilter
   {
      void OnActionExecuting(ActionExecutingContext filterContext);
      void OnActionExecuted(ActionExecutedContext filterContext);
   }
}

ASP.NET MVC provides the following action filters:

  • Output Cache: Caches the output of a controller action for a specified amount of time. One of the important features of output cache is that it supports an action filter that can be called all the time, even when the action is marked with a cache attribute.
    namespace MVCFiltere
    {
       [LogThis]
       [DonutOutputCache(Duration = 5, Order = 100)]
       public ActionResult Index()
    
    }
    
  • Handle Error: A filter that works when you have enabled the custom errors in web.config. The HandleError attribute could be applied over the action method as well as controller level and global level. The HandleError attribute is generally added in the Global.asax.cs file and registered in the Application_Start event.
  • Authorize: This action filter enables developers to restrict access to a particular user or role.

Result Filters

Result filters contain logic for executing before or after generating the result for an action. The IResultFilter interface is used to create a Result Filter.

Result filters are performed through the IResultFilter interface. That interface provides two methods: OnResultExecuting and OnResultExecuted. These methods will be executed before or after generating the result for an action.

namespace MVCFiltere
{
   public interface IResultFilter
   {
      void OnResultExecuting(ResultExecutingContext filterContext);
      void OnResultExecuted(ResultExecutedContext filterContext);
   }
}

Exception Filters

Exception filters are used for handling errors. Exception filters can catch an exception caused by either a controller action or controller action results. Exception filters are also used for logging the exceptions. The IExceptionFilter interface is used to create an Exception Filter which provides the OnException method which will be executed when exception occurs during the action’s execution or filter’s execution.

namespace MVCFiltere
{
   public interface IExceptionFilter
   {
      void OnException(ExceptionContext filterContext);
   }
}

Conclusion

I tried to explain the types of Filters that are being used in the MVC framework in this article. I hope you will enjoy writing ASP.NET MVC filters while working on ASP.NET MVC framework projects. Thanks for reading.

More by Author

Previous article
Next article

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read