ASP.NET Core MVC Intermediate

Filters and the filter pipeline

Filters let you run code before and after specific stages of an MVC action, such as authorization, model binding, the action itself and the result. This lesson shows the filter pipeline, the filter types and how to write and register your own.

The MVC filter pipeline
  1. StartAuthorization filtersRun first and can stop the request if the user is not allowed
  2. Step 2Resource filters (before)Can short-circuit, for example to return a cached result
  3. Step 3Model bindingAction parameters are filled from the request
  4. Step 4Action filters (before)Can inspect or change the arguments
  5. Step 5Action methodYour code runs and returns a result
  6. Step 6Action filters (after)Can inspect or replace the result
  7. Step 7Result filtersRun around the execution of the result, such as rendering a view
  8. EndResponse is writtenResource filters (after) get the last word

Exception filters run only when an unhandled exception is thrown by the action or earlier filters.

The idea in plain words

Some code applies to many actions: logging, checking permissions, adding headers, handling errors. Instead of repeating it in every action, you write it once as a filter and attach it as an attribute on an action or controller, or register it globally for all actions.

Filters run inside MVC, after routing has chosen the action, so they can see things middleware cannot, such as the action arguments, ModelState and the IActionResult.

  • Authorization filters: decide whether the user may run the action.
  • Resource filters: wrap most of the pipeline, useful for caching.
  • Action filters: run just before and after the action method.
  • Exception filters: handle unhandled exceptions from actions.
  • Result filters: run before and after the result executes.

Example: an action filter

This filter logs how long each action takes. It is registered globally, so every controller action is timed.

C#
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc.Filters;

public class TimingFilter : IActionFilter
{
    private readonly ILogger<TimingFilter> _logger;
    private Stopwatch? _watch;

    public TimingFilter(ILogger<TimingFilter> logger) => _logger = logger;

    public void OnActionExecuting(ActionExecutingContext context)
        => _watch = Stopwatch.StartNew();

    public void OnActionExecuted(ActionExecutedContext context)
        => _logger.LogInformation("{Action} took {Ms} ms",
            context.ActionDescriptor.DisplayName, _watch?.ElapsedMilliseconds);
}

// Program.cs
builder.Services.AddControllersWithViews(options =>
    options.Filters.Add<TimingFilter>());

Common mistakes

Filters are powerful, so it is easy to put too much in them.

  • Using a filter for logic that applies to every request, including static files. That belongs in middleware.
  • Expecting an exception filter to catch errors from middleware or view rendering outside MVC. Use the exception handler middleware for app-wide errors.
  • Putting business rules in filters, which hides them from people reading the action.

Interview question

In what order do ASP.NET Core MVC filters run?

Authorization filters run first, then resource filters, then model binding, then action filters before the action, the action itself, action filters after it, then result filters around the result execution, and finally the after part of resource filters. Exception filters run only if an unhandled exception occurs in the action or the filters before the result. Within the same type, global filters wrap controller filters, which wrap action filters.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.