Advertisement

Filters interview questions and answers

15 Filters interview questions for ASP.NET Core roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q1 Beginner Save

What are MVC filters in ASP.NET Core, and what are the main filter types in the pipeline (authorization, resource, action, exception, result)?

Filters let you run code at specific stages surrounding an MVC action's execution: Authorization filters run first (checking access before anything else), Resource filters wrap the rest of the pipeline (before model binding and after result execution), Action filters run immediately before/after the action method itself, Exception filters handle unhandled exceptions from the action, and Result filters wrap the execution of the action's result -- each type serves a distinct purpose in the request/response lifecycle.
public class LogActionFilter : IActionFilter {
    public void OnActionExecuting(ActionExecutingContext context) {
        Console.WriteLine($"Executing {context.ActionDescriptor.DisplayName}");
    }
    public void OnActionExecuted(ActionExecutedContext context) {
        Console.WriteLine($"Executed {context.ActionDescriptor.DisplayName}");
    }
}
Real-world example
A logging action filter automatically records the start and end of every controller action's execution across an entire application, without needing to add manual logging statements to each individual action method.
Likely follow-ups
  • In what order do these different filter types execute relative to each other?
  • How do filters differ from middleware in terms of scope and capabilities?
ASP.NET Core Middleware & Request Pipeline Logging
Q2 Intermediate Save

How do you apply a filter globally to every controller action, versus scoping it to a specific controller or individual action?

Global filters are registered via options.Filters.Add() in AddControllers(), applying to every action in the application. Controller-scoped filters are applied as an attribute directly on the controller class, affecting all its actions. Action-scoped filters are applied as an attribute on an individual action method, affecting only that specific action -- letting you choose the appropriate breadth for each filter's concern.
// Global: applies to every controller action
builder.Services.AddControllers(options => {
    options.Filters.Add<LogActionFilter>();
});

// Controller-scoped: applies only to this controller's actions
[TypeFilter(typeof(AuditFilter))]
public class AdminController : ControllerBase { }

// Action-scoped: applies only to this one action
[TypeFilter(typeof(RateLimitFilter))]
[HttpGet("expensive-report")]
public IActionResult GetReport() { ... }
Real-world example
A logging filter is registered globally since every action benefits from consistent request logging, while a specific audit filter is scoped only to the AdminController since only admin actions need that particular extra scrutiny.
Likely follow-ups
  • What determines the execution order when multiple filters of the same type apply to one action?
  • How do you exclude a globally-registered filter from one specific action?
Configuration & Options Pattern RESTful Web APIs & Controllers
Q3 Advanced Save

How does an IAsyncActionFilter differ from the synchronous IActionFilter, and why is the async version generally preferred for filters doing I/O work?

IAsyncActionFilter's single OnActionExecutionAsync method receives an ActionExecutionDelegate you explicitly await to continue the pipeline (giving you a single, clear place for both before and after logic wrapping the call), whereas IActionFilter's OnActionExecuting/OnActionExecuted pair are synchronous methods -- for filters performing I/O (a database call to check a feature flag, an external API call), the async variant avoids blocking a thread pool thread during that I/O, just as async/await matters anywhere else in the request pipeline.
public class FeatureFlagFilter(IFeatureFlagService flags) : IAsyncActionFilter {
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
        if (!await flags.IsEnabledAsync("NewCheckout")) {
            context.Result = new NotFoundResult();
            return;  // short-circuits, next() never called
        }
        await next();  // continue to the action
    }
}
Real-world example
A feature-flag-checking filter uses the async variant since it needs to call an external feature flag service, avoiding blocking a thread pool thread during that network call the way a synchronous filter making a blocking call would.
Likely follow-ups
  • What happens if you don't call next() inside OnActionExecutionAsync?
  • Can you inspect or modify the action's result after next() returns?
Concurrency (asyncio/threading/multiprocessing) Configuration & Options Pattern
Q4 Intermediate Save

How do you pass constructor parameters or configuration to a filter class using [TypeFilter] or [ServiceFilter]?

[TypeFilter(typeof(MyFilter), Arguments = new object[] { "someValue" })] instantiates the filter via the DI container but lets you pass additional constructor arguments not resolvable from DI. [ServiceFilter(typeof(MyFilter))] instead requires the filter itself to be registered in the DI container and resolves it entirely through DI, appropriate when the filter's dependencies are all standard injectable services with no need for additional per-usage arguments.
// TypeFilter: mix DI-resolved dependencies with explicit arguments
[TypeFilter(typeof(RateLimitFilter), Arguments = new object[] { 100 })]
public IActionResult Get() { ... }

// ServiceFilter: filter itself registered in DI, fully resolved from there
builder.Services.AddScoped<AuditFilter>();
[ServiceFilter(typeof(AuditFilter))]
public IActionResult Delete(int id) { ... }
Real-world example
A rate-limiting filter uses TypeFilter with an explicit request-count argument so different actions can apply the same filter class with different limits (100 vs 10) without needing separate filter classes for each threshold.
Likely follow-ups
  • What's the practical difference in DI lifetime behavior between TypeFilter and ServiceFilter?
  • When would a plain filter attribute (no DI needed) be simpler than either approach?
Dependency Injection Rate Limiting
Q5 Advanced Save

How does IExceptionFilter differ from global exception handling middleware, and when would you choose one over the other?

Exception filters run within the MVC action invocation pipeline specifically, giving access to MVC-specific context (like the ActionDescriptor and ModelState) that middleware-level exception handling doesn't have, but they only catch exceptions from within controller actions -- not from middleware, routing, or minimal API endpoints. Global exception handling middleware (UseExceptionHandler/IExceptionHandler) catches exceptions from the entire pipeline uniformly, making it the more comprehensive, generally-preferred approach, with exception filters reserved for MVC-specific scenarios needing that extra action context.
public class MvcSpecificExceptionFilter : IExceptionFilter {
    public void OnException(ExceptionContext context) {
        if (context.Exception is ValidationException ve) {
            context.Result = new BadRequestObjectResult(new { errors = ve.Errors, action = context.ActionDescriptor.DisplayName });
            context.ExceptionHandled = true;
        }
    }
}
Real-world example
A team uses global exception handling middleware as their primary, comprehensive error-handling mechanism, reserving a narrow exception filter only for one specific controller needing access to MVC action metadata unavailable at the middleware level.
Likely follow-ups
  • Why can't exception filters catch exceptions from middleware or minimal API endpoints?
  • What's the recommended default choice for a new project starting from scratch?
Global Exception Handling & Middleware ASP.NET Core Middleware & Request Pipeline
Q6 Intermediate Save

What is an IResourceFilter, and how does its position in the pipeline (before model binding) make it useful for short-circuiting expensive work?

Resource filters run before model binding occurs and after the result has executed, wrapping nearly the entire remaining pipeline -- their early position (before model binding) makes them ideal for short-circuiting a request cheaply (like returning a cached response or rejecting based on a header check) before the potentially expensive work of binding and validating a complex request body ever happens.
public class CachedResponseFilter : IResourceFilter {
    public void OnResourceExecuting(ResourceExecutingContext context) {
        var cacheKey = context.HttpContext.Request.Path;
        if (_cache.TryGetValue(cacheKey, out IActionResult cached)) {
            context.Result = cached;  // short-circuits BEFORE model binding even runs
        }
    }
    public void OnResourceExecuted(ResourceExecutedContext context) { }
}
Real-world example
A caching resource filter returns a cached response before the framework even attempts to bind and validate the incoming request body, avoiding wasted binding/validation work for requests that will be served entirely from cache anyway.
Likely follow-ups
  • How does this differ in timing from an action filter, which runs after model binding?
  • What's the trade-off of resource filters versus achieving similar short-circuiting via middleware instead?
Caching ASP.NET Core Middleware & Request Pipeline
Q7 Advanced Save

How do you control the execution order of multiple filters of the same type applied to a single action?

Filters implementing IOrderedFilter expose an Order property (defaulting to 0) that determines execution sequence -- lower values execute first for the 'before' phase (OnActionExecuting-style methods) and last for the 'after' phase (OnActionExecuted-style methods, executing in reverse), following a nested onion-like execution model similar to middleware, letting you explicitly control which filter's logic should wrap which other filter's logic when multiple filters of the same type are stacked on one action.
public class FirstFilter : IActionFilter, IOrderedFilter {
    public int Order => 1;
    public void OnActionExecuting(ActionExecutingContext context) => Console.WriteLine("First: before");
    public void OnActionExecuted(ActionExecutedContext context) => Console.WriteLine("First: after");
}

public class SecondFilter : IActionFilter, IOrderedFilter {
    public int Order => 2;
    // Executes: First:before, Second:before, [action runs], Second:after, First:after
}
Real-world example
A team stacking both a logging filter and a validation filter on the same action explicitly sets Order values to guarantee logging always wraps validation (logging both the validation attempt and its outcome) rather than relying on unpredictable default ordering.
Likely follow-ups
  • What's the default order value if IOrderedFilter isn't implemented, and how are ties broken?
  • How does global filter order interact with controller/action-level filter order?
Configuration & Options Pattern Diagnostics & Performance
Q8 Intermediate Save

How does IEndpointFilter provide similar cross-cutting functionality for minimal APIs that MVC filters provide for controllers?

IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext, EndpointFilterDelegate) wraps a minimal API endpoint's execution, letting you inspect/modify arguments before invocation and the result after, applied via .AddEndpointFilter() on individual endpoints or entire route groups -- serving a conceptually similar role to MVC's IAsyncActionFilter but designed specifically for minimal API's lighter-weight style.
public class ValidationFilter<T> : IEndpointFilter {
    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) {
        var arg = context.GetArgument<T>(0);
        if (!IsValid(arg)) return Results.BadRequest("Invalid input");
        return await next(context);
    }
}

app.MapPost("/products", Create).AddEndpointFilter<ValidationFilter<ProductDto>>();
Real-world example
A minimal-API-based project implements one reusable generic ValidationFilter<T> applied across many endpoints accepting different DTOs, replicating [ApiController]'s automatic validation behavior consistently without per-endpoint duplication.
Likely follow-ups
  • How does IEndpointFilter's context.GetArgument access typed parameters compared to MVC's ActionArguments dictionary?
  • Can the same filter logic be shared between MVC action filters and minimal API endpoint filters?
Controllers vs Minimal APIs Model Binding & Validation
Q9 Advanced Save

How would you implement a filter that modifies the action's result based on the outcome, such as wrapping every successful response in a standard envelope?

An IActionFilter/IAsyncActionFilter can inspect and replace context.Result after calling next() (in the 'after' phase), letting you transform whatever the action returned into a standardized shape -- like wrapping successful responses in a consistent envelope with metadata (timestamp, request ID) -- applied globally so every endpoint automatically gets consistent response formatting without each action needing to construct the envelope itself.
public class ResponseEnvelopeFilter : IAsyncActionFilter {
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
        var executed = await next();
        if (executed.Result is ObjectResult objResult && objResult.StatusCode is null or >= 200 and < 300) {
            executed.Result = new ObjectResult(new {
                data = objResult.Value,
                timestamp = DateTime.UtcNow,
                requestId = context.HttpContext.TraceIdentifier
            });
        }
    }
}
Real-world example
An API wraps every successful response in a standard envelope (with data, timestamp, and requestId fields) using a single global action filter, ensuring consistent response formatting across dozens of controllers without each action manually constructing the wrapper.
Likely follow-ups
  • How would you exclude specific actions from this global wrapping behavior?
  • What's the risk of a global filter like this interacting unexpectedly with error responses?
RESTful Web APIs & Controllers Global Exception Handling & Middleware
Q10 Intermediate Save

What is the difference between a filter attribute applied directly (like [MyFilter]) and using [TypeFilter]/[ServiceFilter] to apply the same filter class?

A filter class can be applied directly as an attribute ([MyFilter]) only if it has a parameterless constructor or its dependencies are resolvable in a way attributes support (attributes can't use full constructor DI directly since they're instantiated by the .NET attribute system, not the DI container) -- for filters needing injected services, [TypeFilter]/[ServiceFilter] are required to route instantiation through the DI container instead, since a plain attribute application bypasses DI entirely.
// Direct attribute application: filter must not need DI-injected dependencies
public class SimpleLogFilter : Attribute, IActionFilter {
    public void OnActionExecuting(ActionExecutingContext context) => Console.WriteLine("Logged");
}
[SimpleLogFilter]
public IActionResult Get() { ... }

// Needs DI: must use TypeFilter/ServiceFilter instead
[ServiceFilter(typeof(DatabaseAuditFilter))]  // DatabaseAuditFilter needs an injected DbContext
public IActionResult Delete(int id) { ... }
Real-world example
A team's initial attempt to apply a filter needing an injected ILogger directly as [MyLoggingFilter] fails to compile/resolve correctly, requiring a switch to [ServiceFilter(typeof(MyLoggingFilter))] to properly route construction through DI.
Likely follow-ups
  • Why can't attributes use standard constructor dependency injection directly?
  • What's the performance overhead difference between direct attributes and TypeFilter/ServiceFilter?
Dependency Injection RESTful Web APIs & Controllers

Showing 1–10 of 15