Introduction

ASP.NET MVC provides Filters to execute custom logic before or after specific stages of request processing. Filters help developers handle cross-cutting concerns such as authentication, authorization, logging, and exception handling without writing repetitive code inside controllers.

In this article, we will learn:

What Are Filters in ASP.NET MVC?

Filters are attributes that can be applied to:

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

Why Use Filters?

ASP.NET MVC Request Life Cycle

Understanding where filters fit in the MVC pipeline is important.

MVC Request Flow:

  1. Request received

  2. Routing

  3. Controller initialization

  4. Filters execution

  5. Action method execution

  6. Result execution

  7. 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:

  1. Authorization Filters

  2. Action Filters

  3. Result Filters

  4. Exception Filters

  5. 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

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

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 Filter Registration Example

filters.Add(new LogActionFilter());

Order of Execution of Filters

The execution order of filters is:

  1. Authentication Filters

  2. Authorization Filters

  3. Action Filters

  4. Result Filters

  5. Exception Filters

Understanding this order helps prevent unexpected behavior.

Advantages of Using Filters

Real-World Use Case

Scenario: Logging user activity across the application.

Solution:
Create a global action filter to log:

This avoids writing logging logic in every controller.

Best Practices

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.