Filters
Think of filters as checkpoints around controller actions.
Request
→ Authorization
→ Resource
→ Action
→ Action Result
→ Result
Response
What is a Filter? (One-liner)
A filter lets you run code before, after, or instead of a controller action.
Used for:
- Auth / Authorization
- Validation
- Logging
- Caching
- Error handling
📌 Interview version:
"Filters handle cross-cutting concerns without polluting controller logic."
Why Filters (not Controllers)?
| Problem | Filters solve it |
|---|---|
| Repeated logic | Reuse across actions |
| Fat controllers | Keep actions clean |
| Cross-cutting concerns | Centralized handling |
Filter Types (MUST MEMORIZE)
🔑 Order of execution (most important)
Authorization
→ Resource
→ Action
→ Result
→ Exception (on error)
Filter Types Cheat Sheet
| Filter | Interface | Purpose |
|---|---|---|
| Authorization | IAuthorizationFilter | Can user access? |
| Resource | IResourceFilter | Cache / resource setup |
| Action | IActionFilter | Before & after action |
| Result | IResultFilter | Before & after response |
| Exception | IExceptionFilter | Handle errors |
📌 Interview tip:
"Authorization filters run first, result filters run last."
Action Filters (Most Common)
Interface
IActionFilter;
IAsyncActionFilter;
Hooks
OnActionExecuting; // before action
OnActionExecuted; // after action
Typical Uses
- Validate parameters
- Log requests
- Modify ViewData
- Short-circuit execution
Short-Circuiting (VERY IMPORTANT)
context.Result = new BadRequestResult();
📌 Meaning:
Action method will NOT run
Used for:
- Validation failure
- Auth failure
- Cached responses
Async Filters (Modern Apps)
Use when you:
- Call DB
- Call API
- Do async work
IAsyncActionFilter;
await next(); // continue pipeline
📌 Interview line:
"Async filters prevent thread blocking."
Result Filters
Interface
IResultFilter;
IAsyncResultFilter;
Runs:
- Before response
- After response
Common Uses
- Add headers
- Modify response
- Logging
IAlwaysRunResultFilter ⭐ (Advanced but impressive)
Runs even if the pipeline short-circuits or fails
Used for:
- Final logging
- Cleanup
- Guaranteed headers
📌 Limitation: ❌ Cannot change the result ✅ Can observe / clean up
Resource Filters
Interface
IResourceFilter;
Runs:
- Before model binding
- Before action
Used for:
- Caching
- Performance timing
- Feature flags
📌 Interview sentence:
"Resource filters wrap the entire MVC execution."
9️⃣ Authorization Filters
Interface
IAuthorizationFilter;
Purpose:
- Check authentication
- Check permissions
Short-circuit example:
context.Result = new UnauthorizedResult();
📌 Runs before model binding
Exception Filters
Interface
IExceptionFilter;
Purpose:
- Catch exceptions
- Log errors
- Return custom responses
context.ExceptionHandled = true;
📌 Interview tip:
Middleware is preferred for global exception handling, filters for MVC-specific cases.
Filter Application Levels
| Level | How |
|---|---|
| Global | Program.cs |
| Controller | Attribute |
| Action | Attribute |
TypeFilter vs ServiceFilter (COMMON QUESTION)
| Filter | When to use |
|---|---|
TypeFilter | Needs constructor arguments |
ServiceFilter | Already registered in DI |
📌 Interview answer:
"ServiceFilter resolves from DI; TypeFilter creates instances dynamically."
Filter Order Control
Two ways:
OrderpropertyIOrderedFilter
Lower number = runs earlier
Filter Overrides
Skip logic
[NonAction]→ not an action- Custom
[SkipFilter]→ opt-out
Pattern:
if (context.Filters.OfType<SkipFilter>().Any()) return;
Filters vs Middleware (VERY IMPORTANT)
| Filters | Middleware |
|---|---|
| MVC only | Global pipeline |
| Action-aware | Request-aware |
| Controller logic | Infrastructure logic |
📌 Interview sentence:
"Middleware handles HTTP, filters handle MVC actions."
30-Second Interview Answer
"ASP.NET Core filters allow us to run logic before or after controller actions to handle cross-cutting concerns like authorization, validation, logging, and caching. There are several filter types—authorization, resource, action, result, and exception—each running at different stages of the MVC pipeline. Filters support dependency injection, async execution, ordering, and short-circuiting, which helps keep controllers clean and reusable."
If You Remember ONLY 7 Things
- Filters wrap controller actions
- Authorization runs first
- Result runs last
- Action filters are most common
- Short-circuit =
context.Result - Async filters for DB/API work
- Middleware ≠ filters