1 questionFilters in ASP.NET Core MVC are pieces of code that let you run logic before or after specific stages of the request pipeline within the MVC framework, such as before an action method executes, after it executes, or when an exception occurs. Common filter types include Authorization filters for access control, Action filters for logic that wraps around action execution, Exception filters for centralized error handling, and Result filters for logic around how results are formatted, and they can be applied globally, at the controller level, or on individual action methods.
public class LogActionFilter : IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
Console.WriteLine("Action starting");
}
public void OnActionExecuted(ActionExecutedContext context) {
Console.WriteLine("Action finished");
}
}
[ServiceFilter(typeof(LogActionFilter))]
public IActionResult GetOrders() { return Ok(); }
Real-world example
An API applies a custom authorization filter across all of its controllers to automatically reject any request that does not include a valid API key, centralizing this security check instead of repeating it in every action method.
Likely follow-ups
- What is the execution order of different filter types in ASP.NET Core?
- How do you create a global filter that applies to every controller?
Middleware & Request Pipeline How is Logging handled in .NET Core?