MVC-Filters


In the context of the ASP.NET MVC framework, filters are used to execute code before or after specific stages in the request processing pipeline. Filters can handle cross-cutting concerns, such as authentication, authorization, logging, and error handling, across multiple actions or controllers.

MVC Filters

There are several types of filters in MVC, each serving a different purpose.

1. Authorization Filter

Used to perform authentication and authorization before an action method is executed. It ensures that the user is authorized to access a particular action or controller.

Executed At - Before the Action Filter and Action Method.

Example - AuthorizeAttribute

You can use this filter to restrict access to certain users or roles.

Authorization Filter Example

Let's say you have an admin panel that only authorized users should access.

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Output

  • If a user with the Admin role accesses the Index action, they see the admin panel view.

  • If a user without the Admin role tries to access it, they are redirected to the login page or shown an unauthorized message.

2. Action Filter

Used to perform logic before and after an action method executes. Commonly used for logging, validation, or modifying data.

Executed At - Before and after the execution of an action method.

Example - ActionFilterAttribute

Action Filter Example

Suppose you want to log the execution time of each action method.

public class LogExecutionTimeAttribute : ActionFilterAttribute
{
    private Stopwatch stopwatch;
    
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        stopwatch = Stopwatch.StartNew();
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        stopwatch.Stop();
        var executionTime = stopwatch.ElapsedMilliseconds;
        filterContext.HttpContext.Response.Headers.Add("X-Execution-Time", executionTime.ToString());
    }
}

[LogExecutionTime]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Output

  • The response header will include the execution time of the Index action.

  • Example - X-Execution-Time: 15

3. Result Filter

Used to perform logic before and after a result (like a ViewResult or JsonResult) is executed. Useful for operations like modifying the response or adding headers.

Executed At - Before and after the ActionResult executes.

Example - OutputCacheAttribute (for caching responses)

Result Filter Example

Let's say you want to add a custom header to the response of an action.

public class AddCustomHeaderAttribute : ResultFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Headers.Add("X-Custom-Header", "This is a custom header");
    }
}

[AddCustomHeader]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Output

  • The response header will include the custom header.

  • Example - X-Custom-Header: This is a custom header

4. Exception Filter

Used to handle unhandled exceptions that occur in controllers or actions. It is commonly used to log errors or show custom error pages.

Executed At - Only when an exception occurs during the execution of an action method or result.

Example - HandleErrorAttribute

Exception Filter Example

Suppose you want to log exceptions globally in your application.

public class GlobalExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        filterContext.Result = new RedirectToRouteResult(
            new System.Web.Routing.RouteValueDictionary
            {
                { "controller", "Error" },
                { "action", "Index" }
            });
        filterContext.ExceptionHandled = true;
    }
}

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new GlobalExceptionFilter());
}

Output

  • If an exception occurs, the user is redirected to the Error controller's Index action.

  • The exception details are logged.


Next