ASP.NET MVC offers filters to run custom logic either prior to or following particular request processing phases. Without having to write repetitious code inside controllers, filters assist developers in managing cross-cutting issues like authentication, authorization, logging, and exception handling.

In this article, we will learn:

What filters are in ASP.NET MVC

  • Types of filters
  • Execution order of filters
  • How to create custom filters
  • Real-world use cases

What Are Filters in ASP.NET MVC?
Filters are attributes that can be applied to:

  • Controllers
  • Action methods
  • Entire application (global filters)

They allow developers to run logic before or after an action method executes.

Why Use Filters?

  • Code reusability
  • Separation of concerns
  • Cleaner controllers
  • Centralized logic

ASP.NET MVC Request Life Cycle
Understanding where filters fit in the MVC pipeline is important.

MVC Request Flow:

  • Request received
  • Routing
  • Controller initialization
  • Filters execution
  • Action method execution
  • Result execution
  • Response returned

Filters act as checkpoints during this lifecycle.

Types of Filters in ASP.NET MVC

ASP.NET MVC provides the following types of filters:

  • Authorization Filters
  • Action Filters
  • Result Filters
  • Exception Filters
  • Authentication Filters (MVC 5)

1. Authorization Filters
Authorization filters are used to check whether a user is authorized to access a resource.

Built-in Authorize Attribute

[Authorize]
public ActionResult Dashboard()
{
    return View();
}

This allows only authenticated users to access the action.

Custom Authorization Filter

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return httpContext.User.Identity.IsAuthenticated;
    }
}


Usage:
[CustomAuthorize]
public ActionResult Profile()
{
    return View();
}

2. Action Filters
Action filters execute logic before and after an action method.
Action Filter Methods

  • OnActionExecuting
  • OnActionExecuted

Example: Custom Action Filter
public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Debug.WriteLine("Action Method Executing");
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        Debug.WriteLine("Action Method Executed");
    }
}


Usage:
[LogActionFilter]
public ActionResult Index()
{
    return View();
}


3. Result Filters
Result filters execute before and after the action result (such as ViewResult).
Result Filter Methods

  • OnResultExecuting
  • OnResultExecuted


Example
public class ResultFilter : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        Debug.WriteLine("Result Executing");
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        Debug.WriteLine("Result Executed");
    }
}

4. Exception Filters
Exception filters handle unhandled exceptions that occur during action execution.
Example: Custom Exception Filter
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new ViewResult
        {
            ViewName = "Error"
        };
    }
}


Register Exception Filter Globally
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new CustomExceptionFilter());
}


5. Authentication Filters (ASP.NET MVC 5)
Authentication filters run before authorization filters and are used to verify user identity.
public class CustomAuthenticationFilter : IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        // Authentication logic
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        // Challenge logic
    }
}


Filter Scope Levels
Filters can be applied at different levels:

  • Global Level – Applies to entire application
  • Controller Level – Applies to specific controller
  • Action Level – Applies to specific action

Global Filter Registration Example
filters.Add(new LogActionFilter());

Order of Execution of Filters
The execution order of filters is:

  • Authentication Filters
  • Authorization Filters
  • Action Filters
  • Result Filters
  • Exception Filters

Understanding this order helps prevent unexpected behavior.

Advantages of Using Filters

  • Promotes clean architecture
  • Reduces duplicate code
  • Improves maintainability
  • Centralized handling of common logic
  • Enhances application performance

Real-World Use Case
Scenario: Logging user activity across the application.

Solution:
Create a global action filter to log:

  • Controller name
  • Action name
  • Request time

This avoids writing logging logic in every controller.

Best Practices

  • Keep filters lightweight
  • Avoid business logic inside filters
  • Use global filters wisely
  • Handle exceptions centrally
  • Use attributes only where required

Conclusion
Filters in ASP.NET MVC play a vital role in building clean, scalable, and maintainable applications. They help manage cross-cutting concerns efficiently and reduce repetitive code. Understanding filter types, execution order, and scope will help developers write better MVC applications.

Mastering filters is essential for any ASP.NET MVC developer.