ASP.NET Core Middleware Pipeline
Give a real production-style example of using ASP.NET Core Middleware Pipeline. Walk through the scenario end-to-end.
Answers use simple, clear English.
Quick interview answer
Scenario: Custom correlation ID middleware adds X-Request-Id header before logging middleware runs. Implementation notes: Follow Microsoft template order; use MapWhen for branch pipelines.
Detailed answer
Scenario: Custom correlation ID middleware adds X-Request-Id header before logging middleware runs. Implementation notes: Follow Microsoft template order; use MapWhen for branch pipelines. Core: Request flows through middleware chain: Exception → HTTPS → Routing → Auth → Endpoints. Each can short-circuit or call next(). Order matters critically. Real-time example: Custom correlation ID middleware adds X-Request-Id header before logging middleware runs. Pros: Composable cross-cutting pipeline; same model for minimal APIs and MVC. Cons: Wrong order breaks auth/CORS; async middleware must await next(). Common mistakes: Placing UseAuthentication after UseAuthorization; forgetting UseRouting. Best practices: Follow Microsoft template order; use MapWhen for branch pipelines. Audience level: Fresher.
Full explanation
Request flows through middleware chain: Exception → HTTPS → Routing → Auth → Endpoints. Each can short-circuit or call next(). Order matters critically.
Real example & use case
Custom correlation ID middleware adds X-Request-Id header before logging middleware runs.
Pros & cons
Pros: Composable cross-cutting pipeline; same model for minimal APIs and MVC. Cons: Wrong order breaks auth/CORS; async middleware must await next().
Common mistakes
Placing UseAuthentication after UseAuthorization; forgetting UseRouting.
Best practices
Follow Microsoft template order; use MapWhen for branch pipelines.
Follow-up questions
Open one as its own read / solve / listen card