ASP.NET Core MVC Interview Question #98

How can filters be registered globally, on controllers, or on actions?

Advanced Routing, Filters, Areas & Application Structure Mid-Level Intermediate

Quick Interview Answer

Global filters are added to MVC options and apply broadly to MVC requests. Attribute-based filters can be placed on a controller to affect all of its actions or on a specific action for narrower scope.

Detailed Explanation

Global filters are added to MVC options and apply broadly to MVC requests. Attribute-based filters can be placed on a controller to affect all of its actions or on a specific action for narrower scope.

Choose the smallest scope that correctly represents the concern. A global filter is appropriate only when the behavior genuinely belongs to the entire MVC application.

Code Example

builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<AuditActionFilter>();
});

// Or:
[ServiceFilter(typeof(AuditActionFilter))]
public IActionResult Edit(int id) => View();