How do you apply a filter globally to every controller action, versus scoping it to a specific controller or individual action?
Short answer
Global filters are registered via options.Filters.Add() in AddControllers(), applying to every action in the application. Controller-scoped filters are applied as an attribute directly on the controller class, affecting all its actions.
Advertisement
AModel answer
Global filters are registered via options.Filters.Add() in AddControllers(), applying to every action in the application. Controller-scoped filters are applied as an attribute directly on the controller class, affecting all its actions. Action-scoped filters are applied as an attribute on an individual action method, affecting only that specific action -- letting you choose the appropriate breadth for each filter's concern.
// Global: applies to every controller action
builder.Services.AddControllers(options => {
options.Filters.Add<LogActionFilter>();
});
// Controller-scoped: applies only to this controller's actions
[TypeFilter(typeof(AuditFilter))]
public class AdminController : ControllerBase { }
// Action-scoped: applies only to this one action
[TypeFilter(typeof(RateLimitFilter))]
[HttpGet("expensive-report")]
public IActionResult GetReport() { ... }Real-world example
A logging filter is registered globally since every action benefits from consistent request logging, while a specific audit filter is scoped only to the AdminController since only admin actions need that particular extra scrutiny.
Likely follow-ups
- What determines the execution order when multiple filters of the same type apply to one action?
- How do you exclude a globally-registered filter from one specific action?
Related topics