📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is middleware in ASP.NET Core? Explain Use, Run and Map (and UseWhen/MapWhen), why the order you register middleware matters, and how you write custom middleware, convention-based versus IMiddleware.

ASP.NET Core middleware: RequestDelegate, Use/Run/Map/MapWhen/UseWhen, the recommended built-in order, short-circuiting, and writing custom middleware as a convention-based class (singleton, scoped services via InvokeAsync parameters) or as IMiddleware (resolved from DI per request).

Junior Theory Intermediate aspnet-core dependency-injection imiddleware middleware request-pipeline

🎯 Key points

  • Middleware is a RequestDelegate (HttpContext -> Task) for cross-cutting concerns (exceptions, auth, logging, headers) that can run code before and after calling next, or short-circuit
  • Use adds middleware that can call next; Run adds terminal middleware; Map branches the pipeline by path prefix
  • UseWhen runs a sub-pipeline only when its predicate is true and then always continues with the main pipeline; MapWhen branches and never rejoins
  • Order is registration order on the way in and reverse on the way out; a short-circuit means nothing registered after it runs
  • Recommended order: exception handler, HSTS/HTTPS redirection, static files, routing, CORS, authentication, authorisation, rate limiter, endpoints
  • Convention-based middleware is constructed once (effectively a singleton); inject scoped services as InvokeAsync parameters
  • IMiddleware is resolved from DI per request via IMiddlewareFactory, so it can be registered scoped or transient (a singleton registration works but loses that benefit)
  • Always await next(context); a missing await lets the response complete while downstream code is still running

⏱ 30-second answer

Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.

🗣 Full answer (senior)

How I would answer this in an interview

"Middleware is how ASP.NET Core handles anything cross-cutting. Each piece is a RequestDelegate, a function from HttpContext to Task, and it gets a reference to the next one. It can inspect or change the request, call next, then inspect or change the response on the way back. If it doesn't call next, it short-circuits: static files does that when it finds a file, and so does the CORS preflight handling.

Use adds a middleware that can call next. Run adds a terminal one. Map("/admin", ...) creates a separate branch for that path prefix, MapWhen does the same on any condition, and UseWhen runs a branch conditionally and then rejoins the main pipeline, which is handy for something like extra logging on /api only. Order is everything because each registration wraps the next: the exception handler has to be first so it can catch what everything after it throws, routing has to come before authorisation so authorisation knows which endpoint and policy apply, and static files usually comes before authentication so the CSS doesn't need a cookie check.

For custom middleware I write a class with a constructor taking RequestDelegate and an InvokeAsync(HttpContext) method. The mistake I see is injecting a scoped service like a DbContext into that constructor: convention-based middleware is created once, so that DbContext becomes a singleton shared across requests. Scoped services go in as InvokeAsync parameters, or I implement IMiddleware, which is resolved from DI on every request. Middleware is for things that apply to every request; anything that depends on which endpoint or model you're dealing with belongs in a filter instead."


Use, Run, Map and friends

Method Calls next? Rejoins main pipeline? Typical use
Use Yes (optionally) n/a Logging, headers, timing
Run No (terminal) n/a Fallback response
Map("/path", b => ...) Branch has its own chain No Separate sub-app, e.g. /health
MapWhen(predicate, ...) Branch has its own chain No Branch by header or query
UseWhen(predicate, ...) Yes Yes Extra middleware for a subset of requests

The recommended order

Request ─► UseExceptionHandler ─► UseHsts ─► UseHttpsRedirection ─► UseStaticFiles (or MapStaticAssets)
        ─► UseRouting ─► UseCors ─► UseAuthentication ─► UseAuthorization ─► UseRateLimiter
        ─► (custom middleware) ─► Endpoints
Response flows back through the same list in reverse.

Convention-based vs IMiddleware

Convention-based IMiddleware
Created Once, at pipeline build Per request, from DI
Registration app.UseMiddleware<T>() only services.AddScoped<T>() + app.UseMiddleware<T>()
Scoped dependencies InvokeAsync parameters Constructor
Strong typing Method found by convention Interface

Production example

A correlation-id middleware placed first in the pipeline adds one header read and one BeginScope per request, costing microseconds, yet it turned a 40-minute log search during an incident into a single query on the id the customer quoted from the error page.

🔍 What the interviewer is checking

Checks that the candidate understands the pipeline mechanics and can write middleware that is safe under concurrency.

Green flags

  • Explains next, short-circuiting and in/out order.
  • Knows the difference between Use, Run, Map and UseWhen.
  • Knows convention-based middleware is a singleton and how to get scoped services.
  • Gives a sensible order for the built-in middleware.

Red flags

  • Cannot explain why the order matters.
  • Injects a DbContext into a middleware constructor.
  • Uses middleware for per-action validation.

📚 Learn in depth

1. What a middleware really is

public delegate Task RequestDelegate(HttpContext context);

IApplicationBuilder.Use takes a Func<RequestDelegate, RequestDelegate>: given the next delegate, return a new one that wraps it. When the app starts, the builder folds the list from the end, so the first registered middleware becomes the outermost function.

build:   endpoint  ←  wrap(authz)  ←  wrap(authn)  ←  wrap(routing)  ←  wrap(exception handler)
run:     exception handler( routing( authn( authz( endpoint ))))

2. Short-circuiting

If a middleware returns without calling next, nothing after it runs. Examples in the framework: StaticFileMiddleware (file found), CorsMiddleware for preflight OPTIONS, HttpsRedirectionMiddleware (sends a 307/308). In .NET 8+, endpoints can call .ShortCircuit() so routing executes them immediately without running the rest of the middleware.

3. Branching

  • Map strips the matched prefix from Request.Path and moves it to PathBase inside the branch.
  • MapWhen evaluates a predicate per request.
  • UseWhen builds a sub-pipeline whose last step calls back into the main pipeline.

4. Convention-based middleware internals

UseMiddleware<T>() uses reflection once to find a public Invoke or InvokeAsync method returning Task whose first parameter is HttpContext. The instance is created once with constructor injection from the root provider. Extra InvokeAsync parameters are resolved from HttpContext.RequestServices on each call, which is how you get scoped services safely.

5. IMiddleware internals

If T implements IMiddleware, UseMiddleware<T>() instead uses IMiddlewareFactory to resolve T from the request's scope on each request and releases it afterwards. That costs a DI resolution per request but gives a normal constructor and a lifetime you choose.

6. Writing headers safely

After await next(context) the response may already have started. To add headers on the way out, register context.Response.OnStarting(() => { ... }) before calling next.

Try it yourself

  1. Register three app.Use lambdas that log "before" and "after"; confirm the nesting order.
  2. Write a convention-based middleware that injects a scoped service in the constructor; run in Development and read the scope validation error.
  3. Rewrite it with IMiddleware and register it as scoped.
  4. Use UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), ...) to add a header only to API responses.
  5. Add a header after await next on a large response and observe the InvalidOperationException; fix it with OnStarting.

💻 Code

A convention-based correlation-id middleware, a convention-based middleware taking a scoped service per call, and an IMiddleware alternative.

// CorrelationIdMiddleware.cs
namespace Shop.Api.Middleware;

// Convention-based: created ONCE, so only singleton-safe dependencies in the constructor
public sealed class CorrelationIdMiddleware(RequestDelegate next, ILogger<CorrelationIdMiddleware> logger)
{
    private const string Header = "X-Correlation-Id";

    public async Task InvokeAsync(HttpContext context)
    {
        var id = context.Request.Headers[Header].FirstOrDefault() ?? context.TraceIdentifier;

        // Headers must be set before the response starts
        context.Response.OnStarting(() =>
        {
            context.Response.Headers[Header] = id;
            return Task.CompletedTask;
        });

        using (logger.BeginScope(new Dictionary<string, object> { ["CorrelationId"] = id }))
        {
            await next(context); // always awaited
        }
    }
}

// Convention-based with a SCOPED dependency: extra InvokeAsync parameters are resolved
// from HttpContext.RequestServices on every request, so each request gets its own instance
public sealed class RequestQuotaMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context, IQuotaStore quota) // scoped, per request
    {
        if (!await quota.TryConsumeAsync(context.User.Identity?.Name ?? "anon", context.RequestAborted))
        {
            context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
            return; // short-circuit: nothing after this middleware runs
        }
        await next(context);
    }
}

// IMiddleware: resolved from DI per request, so scoped dependencies are fine in the constructor
public sealed class TenantAuditMiddleware(IAuditStore audit) : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        await next(context);
        await audit.RecordAsync(context.Request.Path, context.Response.StatusCode, context.RequestAborted);
    }
}

public interface IAuditStore { Task RecordAsync(string path, int status, CancellationToken ct); }
public interface IQuotaStore { Task<bool> TryConsumeAsync(string key, CancellationToken ct); }
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IAuditStore, SqlAuditStore>();
builder.Services.AddScoped<IQuotaStore, SqlQuotaStore>();
builder.Services.AddScoped<TenantAuditMiddleware>(); // IMiddleware must be registered

var app = builder.Build();
app.UseExceptionHandler("/error");
app.UseMiddleware<CorrelationIdMiddleware>();       // early, so every log line has the id
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<RequestQuotaMiddleware>();
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"),
    branch => branch.UseMiddleware<TenantAuditMiddleware>()); // only API calls are audited, then rejoins
app.MapGet("/api/orders", () => TypedResults.Ok(Array.Empty<string>()));
app.Run();

⚠ Common mistakes

  • Mistake: Injecting a scoped service (for example a DbContext) into a convention-based middleware constructor. Why it is wrong: The middleware is created once, so one DbContext is shared across concurrent requests. Instead: Add it as an InvokeAsync parameter or implement IMiddleware.
  • Mistake: Calling next(context) without awaiting it (or returning Task.CompletedTask after starting it). Why it is wrong: Your middleware finishes while downstream code is still running, so 'after' logic runs too early, scopes are disposed under the endpoint, and exceptions go unobserved. Instead: Always await next(context).
  • Mistake: Registering UseExceptionHandler late in the pipeline. Why it is wrong: It only catches exceptions thrown by middleware registered after it. Instead: Register it first.
  • Mistake: Using Run where Use was intended. Why it is wrong: Run is terminal; nothing after it executes, including your endpoints. Instead: Use Use and call next.
  • Mistake: Writing to the response and then calling next. Why it is wrong: The next component may try to set headers or status after the body started, causing exceptions or corrupted responses. Instead: Either short-circuit or call next, not both.
  • Mistake: Forgetting to register an IMiddleware type in DI. Why it is wrong: UseMiddleware<T> throws at runtime because the factory cannot resolve it. Instead: services.AddScoped<T>() or AddTransient<T>().
  • Mistake: Putting endpoint-specific logic (model validation, per-action auth) in middleware. Why it is wrong: Middleware doesn't know the action's parameters or model. Instead: Use MVC filters or endpoint filters.

🏛 Senior insight: trade-offs

Middleware is the right tool for concerns that are true for every request regardless of endpoint: correlation ids, security headers, exception handling, request logging. A senior also knows what the framework already gives you, so you don't write your own CORS, rate limiting, response compression or exception handling middleware. When a concern depends on the endpoint, read endpoint metadata after routing (context.GetEndpoint()?.Metadata.GetMetadata<T>()) or use filters.

Option When it fits Cost When not to
Inline app.Use lambda Tiny, app-specific behaviour Hard to test and reuse Anything over ~10 lines
Convention-based class Reusable, hot path Constructor dependencies must be singleton-safe Needs scoped services in many places
IMiddleware Scoped dependencies, clearer typing DI resolution per request Extremely hot paths
Endpoint/MVC filter Depends on the endpoint or its arguments Only runs for matched endpoints Must run for static files or 404s

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes each middleware calling the next or stopping. Why: Checks whether the candidate recognises middleware as a pipeline variant of Chain of Responsibility.
    How to answer

    Chain of Responsibility sends a request along a chain of handlers; each one decides whether to handle it, pass it on, or both, and the sender doesn't know which one acted.

    • Classic variant: the first handler that can deal with it stops the chain, like an expense approval going team lead → manager → director by amount.
    • Pipeline variant: every handler can act before and after calling next. ASP.NET Core middleware (RequestDelegate next) and DelegatingHandler in HttpClient work this way.

    Short-circuiting means returning without calling next: authentication returning 401, static files serving a file, a cache hit. That's why order matters: exception handling must wrap everything, and authentication must run before authorisation.

    The trade-off is decoupling and composability against long implicit chains whose order lives far from the handlers.

  2. When: Candidate says middleware 'wraps' the next component. Why: Checks the related Decorator pattern and how wrapping differs from chaining.
    How to answer

    Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).

    .NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.

    The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().

    The trade-off is that order matters and long chains are harder to debug.

↩ Usually asked after

More in ASP.NET Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me