Skip to the workspace
Pebellslearn by building
ASP.NET Core Basics: Pipeline, Services and Settings  ›  Lesson

Filters and Attributes — Hooks Around an Action

Filters and Attributes 15 minFilters run code at set stages around a controller action or endpoint, and attributes attach them, along with routing and validation rules, directly to the code they affect.

aspnet core / Filters and Attributes — Hooks Around an Action

Explore each scene at your own pace.

01 · The rule

The rule

Filters and Attributes — Hooks Around an Action

Middleware sees every request but knows nothing about which controller action will run. Some rules need that knowledge: "log the arguments of every borrow action", "reject this action if the book has no copies left". Filters hook in around the action itself, and attributes stick them right where they apply.

The rule

Middleware wraps every request; filters wrap the chosen action.

An attribute is metadata in square brackets on a class, method or parameter. You have already used several: [HttpGet], [Route], [ApiController], [FromBody], and validation rules like [Required] and [Range(1, 10)]. Some attributes attach filters, such as [ServiceFilter] below. [Authorize] is metadata too: the authorization middleware reads it and refuses the request before your action is reached.

MVC and Razor Pages run filters in fixed stages:

  1. Authorization filters — custom "may this caller run it?" checks.
  2. Resource filters — before model binding; good for caching.
  3. (model binding and validation)
  4. Action filters — just before and after the action; can see its arguments.
  5. Exception filters — handle exceptions thrown by the action.
  6. Result filters — around the writing of the result.

Any filter can short-circuit by setting a result, and then the action never runs.

public class CopiesAvailableFilter(LibraryDb db) : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(
        ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var bookId = (int)context.ActionArguments["bookId"]!;
        if (await db.CopiesAvailableAsync(bookId) == 0)
        {
            context.Result = new ConflictObjectResult("No copies left.");
            return;                     // the action is skipped
        }
        await next();                   // run the action
    }
}

[HttpPost("{bookId:int}/borrow")]
[ServiceFilter(typeof(CopiesAvailableFilter))]
public IActionResult Borrow(int bookId) { /* ... */ }

Register the filter with builder.Services.AddScoped<CopiesAvailableFilter>(); so [ServiceFilter] can build it. Minimal APIs have their own version: endpoint filters, added with .AddEndpointFilter(...).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.