跳到主要内容

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)?​

ProblemFilters solve it
Repeated logicReuse across actions
Fat controllersKeep actions clean
Cross-cutting concernsCentralized handling

Filter Types (MUST MEMORIZE)​

🔑 Order of execution (most important)​

Authorization
→ Resource
→ Action
→ Result
→ Exception (on error)

Filter Types Cheat Sheet​

FilterInterfacePurpose
AuthorizationIAuthorizationFilterCan user access?
ResourceIResourceFilterCache / resource setup
ActionIActionFilterBefore & after action
ResultIResultFilterBefore & after response
ExceptionIExceptionFilterHandle 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​

LevelHow
GlobalProgram.cs
ControllerAttribute
ActionAttribute

TypeFilter vs ServiceFilter (COMMON QUESTION)​

FilterWhen to use
TypeFilterNeeds constructor arguments
ServiceFilterAlready registered in DI

📌 Interview answer:

"ServiceFilter resolves from DI; TypeFilter creates instances dynamically."


Filter Order Control​

Two ways:​

  1. Order property
  2. IOrderedFilter

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)​

FiltersMiddleware
MVC onlyGlobal pipeline
Action-awareRequest-aware
Controller logicInfrastructure 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​

  1. Filters wrap controller actions
  2. Authorization runs first
  3. Result runs last
  4. Action filters are most common
  5. Short-circuit = context.Result
  6. Async filters for DB/API work
  7. Middleware ≠ filters