UseWhen(predicate, configuration) branches the pipeline conditionally based on a predicate evaluated per request, applying the given middleware chain only when the condition is true, then automatically rejoining the main pipeline afterward -- unlike Map/MapWhen, which create a fully separate branch that typically doesn't rejoin. This is useful for applying middleware (like extra logging) only to specific request types without duplicating the entire remaining pipeline.
app.UseWhen(
context => context.Request.Path.StartsWithSegments("/api"),
apiApp => apiApp.UseMiddleware<ApiKeyValidationMiddleware>()
);
// Non-API requests skip ApiKeyValidationMiddleware entirely, but both paths
// continue through the same remaining pipeline afterward
Real-world example
An application applies API-key validation middleware only to requests under /api using UseWhen, while static file requests and health check endpoints skip that check entirely without needing a completely separate pipeline branch.
Likely follow-ups
How does UseWhen's rejoining behavior differ from Map's branching?
What's a good use case for MapWhen instead of UseWhen?
A commonly recommended order is: exception handling first (to catch errors from everything after it), HTTPS redirection, HSTS, static files (served early to bypass unnecessary processing), routing, CORS (must be after routing, before authorization), authentication, authorization, custom business middleware, then endpoint mapping last. Each position reflects a dependency: authorization needs authentication's identity, CORS decisions need routing's matched endpoint metadata, and exception handling needs to wrap everything to catch downstream failures.
A subtle production bug where CORS headers weren't applied correctly for certain error responses is traced to UseCors being registered before UseRouting instead of after, violating the documented recommended order.
Likely follow-ups
What breaks specifically if CORS is registered before routing?
Does this order change for minimal APIs versus MVC controllers?
CORS & Cross-Origin Resource SharingAuthentication & Authorization (IdentityJWTOAuth)
HttpContext encapsulates everything about a single HTTP request/response cycle -- the request (headers, body, route values), the response (status code, headers, body stream), user identity (once authentication runs), and a Items dictionary for passing arbitrary custom data between middleware components within the same request's lifetime, since each middleware receives the same HttpContext instance as the pipeline executes.
app.Use(async (context, next) => {
context.Items["RequestStartTime"] = DateTime.UtcNow; // stash data for later middleware
await next();
});
app.Use(async (context, next) => {
var start = (DateTime)context.Items["RequestStartTime"];
Console.WriteLine($"Elapsed: {DateTime.UtcNow - start}");
await next();
});
Real-world example
A correlation-ID middleware generates a unique ID early in the pipeline, stores it in context.Items, and every subsequent logging call throughout the request (including deep inside business logic) retrieves it via HttpContext to tag all related log entries consistently.
Likely follow-ups
How does HttpContext.Items differ from HttpContext.Features for passing data?
Why shouldn't you store HttpContext itself in a singleton service?
HttpContext is only valid for the duration of a single request and is reused/recycled by the framework after the request completes -- storing a reference to it in a singleton service can lead to accessing stale, disposed, or cross-request-contaminated data, especially under concurrent load where multiple requests might interleave. The recommended alternative is injecting IHttpContextAccessor, which correctly retrieves the current request's HttpContext via AsyncLocal-based ambient state, though even that should be used judiciously since it introduces implicit dependencies.
// Dangerous: DON'T do this
public class BadSingletonService {
private HttpContext _context; // captured once, becomes stale/wrong across requests
}
// Correct approach
public class GoodService {
private readonly IHttpContextAccessor _accessor;
public GoodService(IHttpContextAccessor accessor) => _accessor = accessor;
public string GetCurrentUserId() => _accessor.HttpContext?.User?.Identity?.Name;
}
Real-world example
A subtle production bug where one user occasionally sees another user's data traced back to a singleton service that had incorrectly cached a reference to an early request's HttpContext instead of using IHttpContextAccessor.
Likely follow-ups
How does IHttpContextAccessor use AsyncLocal to track the ambient context?
Why do many architects still recommend avoiding IHttpContextAccessor when possible?
UseStaticFiles() middleware serves files from the wwwroot folder (by default) directly to clients without routing through MVC/controller logic, handling common concerns like content-type detection, caching headers, and range requests for things like CSS, JavaScript, and images automatically.
var app = builder.Build();
app.UseStaticFiles(); // serves files from wwwroot by default
// Custom directory:
app.UseStaticFiles(new StaticFileOptions {
FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "Assets")),
RequestPath = "/assets"
});
Real-world example
A Blazor Server application relies on UseStaticFiles to serve its compiled CSS and JavaScript bundles directly from wwwroot, bypassing the routing and MVC pipeline entirely for better performance on static assets.
Likely follow-ups
How does UseStaticFiles interact with caching headers like Cache-Control?
What's the security risk of serving files outside the intended directory?
ASP.NET Core Middleware & Request PipelineBlazor (Server & WebAssembly)
Middleware are components chained together into a pipeline that every incoming HTTP request passes through before reaching application logic (and every response passes back through on the way out) -- each middleware component can inspect or modify the request/response, or short-circuit the pipeline entirely (like rejecting an unauthenticated request before it ever reaches a controller), and then calls the next delegate to continue to the next component. Registration order in Program.cs directly determines execution order, so placing authentication after authorization, for instance, would mean authorization runs against a request that hasn't been authenticated yet.
var app = builder.Build();
app.Use(async (context, next) => {
Console.WriteLine($"Request: {context.Request.Path}");
await next(); // passes control to the next middleware in the pipeline
});
app.UseRouting();
app.UseAuthentication(); // must run BEFORE authorization
app.UseAuthorization();
app.MapControllers();
app.Run();
Real-world example
A custom logging middleware registered first in the pipeline records every incoming request's path and timing, while authentication and authorization middleware registered afterward ensure that logging captures even requests that are ultimately rejected for being unauthenticated.
Likely follow-ups
What specifically goes wrong if UseAuthorization() is registered before UseAuthentication()?
How would you write a custom middleware that short-circuits the pipeline for a specific condition?
ASP.NET Core Middleware & Request PipelineAuthentication & Authorization (IdentityJWTOAuth)
Minimal APIs (introduced in .NET 6) let you define HTTP endpoints directly in Program.cs using simple lambda-based route handlers, without the boilerplate of a full controller class -- they fully support dependency injection, middleware, model binding, and authentication despite their simplicity, and are fully compatible with Native AOT compilation. Minimal APIs suit lightweight services, microservices, or simple CRUD APIs prioritizing fast startup and minimal ceremony, while traditional controllers remain preferable for larger applications needing more structure, action filters, or a clear separation of many related endpoints.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/products", () => new[] { "Product1", "Product2" });
app.MapGet("/products/{id}", (int id, IProductService svc) => svc.GetById(id)); // DI still works
app.Run();
Real-world example
A small internal microservice exposing just three simple endpoints (list, get-by-id, create) uses Minimal APIs to avoid the overhead of a full controller class per endpoint, keeping the entire service's routing visible in a single, compact Program.cs file.
Likely follow-ups
How do Minimal APIs handle model validation compared to the [ApiController] attribute's automatic validation in MVC?
At what point does a growing Minimal API codebase typically benefit from being restructured into controllers instead?
Controllers vs Minimal APIs.NET CLISDK & Project Structure (csproj)