What is middleware in ASP.NET Core and how is the pipeline composed?
cs-mid-008
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
Middleware in ASP.NET Core is a component that sits in the HTTP request pipeline. Each piece of middleware receives an HttpContext and a reference to the next middleware (a RequestDelegate). It can perform work before calling next (inbound), call next, and then perform work after (outbound). The pipeline is composed in Program.cs using app.Use, app.Run, or app.Map. Order matters: authentication must come before authorization; exception handling should be first so it wraps everything. Short-circuit middleware (app.Run) terminates the chain without calling next. Custom middleware is implemented as a class with a constructor that takes RequestDelegate and an InvokeAsync method.
Code example
// Inline middleware
app.Use(async (context, next) =>
{
var sw = Stopwatch.StartNew();
await next(context);
sw.Stop();
Console.WriteLine($"{context.Request.Path} took {sw.ElapsedMilliseconds}ms");
});
// Class-based middleware
public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
public RequestTimingMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
var sw = Stopwatch.StartNew();
await _next(context);
context.Response.Headers["X-Response-Time"] = $"{sw.ElapsedMilliseconds}ms";
}
}
// Registration
app.UseMiddleware<RequestTimingMiddleware>();
Follow-up
How does middleware differ from a filter in ASP.NET Core? When would you choose one over the other?