SkillPilotAI

Filters

Filters run code around MVC controller actions: authorization, before/after the action, exception mapping and result changes. They remove copy-pasted cross-cutting code from actions, so nothing is forgotten in one place.

48.1 Why is it used?

  • API key checks, timing logs, exception-to-status mapping and response headers are cross-cutting concerns, not business logic.
  • Copy-paste means one forgotten action becomes a security hole.
  • A filter is written once and applied globally, per controller or per action.
  • Unlike middleware, a filter gets the action context: action name, arguments, ModelState and result.

48.2 The bug: copy-paste in every action

C#
[HttpPost]public ActionResult<OrderDto> Create(    CreateOrderRequest req){    if (Request.Headers["X-Api-Key"] != "dev-key")        return Unauthorized();    try { return store.Place(req.Item, req.Qty); }    catch (OutOfStockException ex)    { return Conflict(ex.Message); }} [HttpDelete("{id:int}")]public IActionResult Cancel(int id)    => store.Cancel(id) ? NoContent() : NotFound();
Output
$ curl -i localhost:5048/api/orders \  -H "Content-Type: application/json" \  -d '{"item":"Mixer Grinder","qty":2}'HTTP/1.1 401 UnauthorizedContent-Type: application/problem+json; charset=utf-8{ "title": "Unauthorized", "status": 401, ... } $ curl -i -X DELETE localhost:5048/api/orders/1HTTP/1.1 204 No ContentServer: Kestrel
  • Create checks the key and catches OutOfStockException itself.
  • The developer forgot to copy the check into Cancel, so DELETE without a key deleted the order (204).
Why copy-paste is wrong
  1. 1.Same check copied into every action

  2. 2.Forgotten in Cancel

  3. 3.DELETE without a key -> 204, order deleted

  4. 4.Need: one place that runs on every action = filters

48.3 The filter pipeline order

Filter pipeline inside MVC
  1. 1.Authorization filter: may the request go further?

  2. 2.Action filter: before + after the action

  3. 3.Action runs (exception filter turns an exception into a response)

  4. 4.Result filter: just before/after the response is written

Any filter can short-circuit by setting context.Result

Filter typeInterface / baseRunsExample here
AuthorizationIAuthorizationFilterFirst, before everythingApiKeyFilter -> 401
ActionIAsyncActionFilterBefore and after the actionLogTimeFilter
ExceptionIExceptionFilterWhen binding/action filters/action throwOutOfStockFilter -> 409
ResultResultFilterAttribute / IResultFilterAround writing the resultAddHeader X-Shop-Region

48.4 Authorization filter: API key

C#
public class ApiKeyFilter : IAuthorizationFilter{    public void OnAuthorization(        AuthorizationFilterContext context)    {        var key = context.HttpContext            .Request.Headers["X-Api-Key"];        if (key != "dev-key")            context.Result =                new UnauthorizedResult();    }}
Output
$ curl -i localhost:5048/api/orders \  -H "Content-Type: application/json" \  -d '{"item":"Mixer Grinder","qty":2}'HTTP/1.1 401 UnauthorizedContent-Type: application/problem+json; charset=utf-8{ "title": "Unauthorized", "status": 401, ... }
  • OnAuthorization reads the X-Api-Key header.
  • Setting context.Result stops the pipeline right there: the action never runs (short circuit).
  • The key is hardcoded for the demo; real login comes with JWT.

48.5 Action filter: before and after

C#
public class LogTimeFilter(ILogger<LogTimeFilter> log)    : IAsyncActionFilter{    public async Task OnActionExecutionAsync(        ActionExecutingContext context,        ActionExecutionDelegate next)    {        var action = context.ActionDescriptor            .RouteValues["action"];        var sw = Stopwatch.StartNew();        await next();        log.LogInformation("{Action} took {Ms} ms",            action, sw.ElapsedMilliseconds);    }}
Output
info: LogTimeFilter[0]      Create took 1 msinfo: LogTimeFilter[0]      Create took 0 msinfo: LogTimeFilter[0]      Cancel took 1 ms
  • The filter gets the action name from ActionDescriptor.RouteValues (middleware does not have this).
  • Code above await next() runs before the action, code below runs after it.

48.6 Registering filters

C#
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(options =>{    options.Filters.Add<LogTimeFilter>();    options.Filters.Add<OutOfStockFilter>();});builder.Services.AddScoped<ApiKeyFilter>();builder.Services.AddSingleton<OrderStore>(); var app = builder.Build(); app.MapControllers(); app.Run();
  • options.Filters.Add<T>() makes a filter global: it runs on every action of every controller.
  • AddScoped<ApiKeyFilter>() registers it in DI so it can be applied with [ServiceFilter<ApiKeyFilter>] on one controller.

48.7 Exception filter: 409 Conflict

C#
public class OutOfStockFilter : IExceptionFilter{    public void OnException(ExceptionContext context)    {        if (context.Exception            is not OutOfStockException ex) return;        context.Result = new ConflictObjectResult(            new ProblemDetails {                Title = "Out of stock",                Detail = ex.Message, Status = 409 });        context.ExceptionHandled = true;    }}
Output
$ curl -i localhost:5048/api/orders \  -H "Content-Type: application/json" \  -H "X-Api-Key: dev-key" \  -d '{"item":"Pressure Cooker","qty":1}'HTTP/1.1 409 ConflictContent-Type: application/problem+json; charset=utf-8{  "title": "Out of stock",  "status": 409,  "detail": "Pressure Cooker is out of stock"}
  • Not an OutOfStockException? return, so other errors still reach normal error handling.
  • ConflictObjectResult with ProblemDetails gives a clean 409.
  • ExceptionHandled = true marks the exception as handled.

48.8 Result filter: a response header

C#
public class AddHeaderAttribute(    string name, string value)    : ResultFilterAttribute{    public override void OnResultExecuting(        ResultExecutingContext context)    {        context.HttpContext.Response            .Headers[name] = value;    }}
Output
$ curl -i localhost:5048/api/orders \  -H "Content-Type: application/json" \  -H "X-Api-Key: dev-key" \  -d '{"item":"Mixer Grinder","qty":2}'HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8X-Shop-Region: IN{"id":2,"item":"Mixer Grinder","qty":2}
  • ResultFilterAttribute makes the class an attribute itself, so it needs no DI.
  • OnResultExecuting runs just before the result is written and adds X-Shop-Region: IN.

48.9 Fix: a clean controller

C#
[ApiController, Route("api/orders")][ServiceFilter<ApiKeyFilter>][AddHeader("X-Shop-Region", "IN")]public class OrdersController(OrderStore store)    : ControllerBase{    [HttpPost]    public ActionResult<OrderDto> Create(        CreateOrderRequest req)        => store.Place(req.Item, req.Qty);    [HttpDelete("{id:int}")]    public IActionResult Cancel(int id)        => store.Cancel(id)            ? NoContent() : NotFound();}
Output
$ curl -i -X DELETE localhost:5048/api/orders/1HTTP/1.1 401 UnauthorizedContent-Type: application/problem+json; charset=utf-8 $ curl -i -X DELETE localhost:5048/api/orders/1 \  -H "X-Api-Key: dev-key"HTTP/1.1 204 No ContentServer: KestrelX-Shop-Region: IN
  • [ServiceFilter<ApiKeyFilter>] at class level protects both Create and Cancel.
  • Create now has no key check and no try/catch: only business logic.
  • Cancel without a key gives 401, with the key 204.

48.10 Checkpoint: a request without a key?

Output
$ curl -i localhost:5048/api/orders \  -H "Content-Type: application/json" \  -d '{"item":"Mixer Grinder","qty":2}'HTTP/1.1 401 UnauthorizedContent-Type: application/problem+json; charset=utf-8Server: Kestrel# no X-Shop-Region header# server log: no LogTimeFilter line
  • The authorization filter runs first; once it sets Result, the action filter and result filter are skipped.
  • So there is no LogTimeFilter line and no X-Shop-Region header.

48.11 Comparison: filter vs middleware

PointMiddlewareFilter
Runs onEvery request (even static files)Only MVC actions
KnowsHttpContext onlyAction name, arguments, ModelState, result
Registeredapp.Use... in Program.csGlobal, controller or action attribute
Use forCORS, compression, request loggingLogic that needs the action context

48.12 Common mistakes

  • Using [ServiceFilter<T>] without registering T in DI: the build passes, every request fails with 500. Register with AddScoped, or use [TypeFilter] which resolves dependencies itself.
  • Myth: an exception filter catches every exception. It only sees exceptions from model binding, action filters and the action; middleware errors are outside it. App-wide: IExceptionHandler.
  • Writing a custom filter for real login and roles: use [Authorize] and policies.
C#
// Wrong: [ServiceFilter<ApiKeyFilter>] used, filter not in DIbuilder.Services.AddControllers(options =>{    options.Filters.Add<LogTimeFilter>();    options.Filters.Add<OutOfStockFilter>();});builder.Services.AddSingleton<OrderStore>(); // DELETE /api/orders/1 -> 500// InvalidOperationException: No service// for type 'ApiKeyFilter' has been registered.

48.13 Rules for filters

  1. Cross-cutting code in filters, business logic in actions.
  2. Filter that needs DI: register it + apply with ServiceFilter (or TypeFilter).
  3. Short circuit: set context.Result.
  4. App-level errors: IExceptionHandler.
  5. Real authentication: [Authorize] + policies.

48.14 Interview tips

  • Filters run inside MVC around the action; order: authorization -> action -> exception -> result.
  • Middleware runs on every request with only HttpContext; a filter gets the action, its arguments and its result.
  • Any filter can short-circuit by setting context.Result.
  • Cross-cutting work like logging goes in filters; DI filters are applied with ServiceFilter.