ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

ASP.NET Core Tutorial• 7 min read

The Middleware Pipeline & Request Lifecycle

Composing the HTTP execution pipeline with app.Use and app.Run

In ASP.NET Core, request processing is managed by a pipeline composed of middleware components. Each component chooses whether to pass the request to the next delegate in the pipeline and can execute work before and after.

Middleware Execution Order Matters

app.Use(...): Executes logic and calls the next() delegate in the chain.

app.Run(...): Terminal middleware that handles the request and terminates the pipeline without forwarding.

Order is critical: Exception handling and security headers must sit near the top of the pipeline, while Authentication and Authorization must precede endpoint routing execution.

Custom Timing Middleware in Program.cs
var app = builder.Build();

// Custom inline timing and logging middleware
app.Use(async (context, next) =>
{
    var stopwatch = System.Diagnostics.Stopwatch.StartNew();
    
    // Invoke the next middleware in the pipeline
    await next(context);
    
    stopwatch.Stop();
    var elapsed = stopwatch.ElapsedMilliseconds;
    
    // Append custom diagnostic header to the response
    context.Response.Headers.Append("X-Response-Time-Ms", elapsed.ToString());
    Console.WriteLine($"[{context.Request.Method}] {context.Request.Path} completed in {elapsed}ms");
});

app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Middleware wraps the request-response flow like an onion, enabling work both before and after execution.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the term for a middleware component that completes the HTTP response and does NOT call the next delegate?