Explain the ASP.NET Core request pipeline.
Quick Answer
A request enters through Kestrel, is handed to the middleware pipeline as an HttpContext, and passes through each middleware in registration order — exception handling, HTTPS redirection, static files, routing, CORS, authentication, authorization — until it reaches the endpoint middleware, which executes your controller action or minimal API handler. The response then travels back out through the same middleware in reverse order.
Kestrel receives the raw request and creates an HttpContext, then hands it to the middleware pipeline. The request flows through each middleware in the order I registered them in Program.cs — exception handling first so it catches everything, then HTTPS redirection, static files, routing, CORS, authentication and authorization — and finally reaches the endpoint middleware, which runs the matched controller action, including model binding and filters. The response then unwinds back through the same middleware in reverse, which is where things like response headers and request-timing logs get added. The key points I'd stress are that order is explicit and matters, that routing has to come before authorization so it knows which endpoint is being protected, and that any middleware can short-circuit and return a response early.
Step by step for a typical API request:
- Kestrel accepts the TCP connection, parses the HTTP request and builds an
HttpContext. - Exception-handling middleware (
UseExceptionHandler/UseDeveloperExceptionPage) wraps everything below it so it can turn unhandled exceptions into a clean response. - HTTPS redirection / HSTS upgrades or enforces the scheme.
- Static files — if the path matches a physical file, this middleware serves it and short-circuits.
- Routing (
UseRouting) matches the request to an endpoint and stores the result on the context, but does not execute it yet. - CORS applies the cross-origin policy.
- Authentication establishes who the caller is (populates
context.User). - Authorization checks whether that user may hit the matched endpoint; returns
401/403if not. - Endpoint middleware (
MapControllers/UseEndpoints) executes the selected action: model binding, filters, the action method, and the result.
Because middleware runs before and after next(), the pipeline is symmetric — response headers, timing and logging added “on the way out” run in reverse order. Ordering rules that matter in interviews: routing before authorization, authentication before authorization, exception handling first, static files early so they skip the rest.
var app = builder.Build();
if (app.Environment.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/error");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting(); // match the endpoint
app.UseCors();
app.UseAuthentication(); // who are you?
app.UseAuthorization(); // are you allowed?
app.MapControllers(); // execute the endpoint
app.Run();