Lesson 8 of 8
Mini Project: Request Logging & Correlation Middleware
Build a complete middleware stack: correlation ID injection, structured request/response logging with timing, global exception handler with ProblemDetails, security headers, and rate limiting - forming the production-ready cross-cutting concerns layer for any ASP.NET Core API.
Quick Quiz - Middleware Pipeline
Complete Middleware Stack
// ━━ Complete production middleware pipeline ━━
var builder = WebApplication.CreateBuilder(args);
// Register middleware as services (IMiddleware pattern)
builder.Services.AddScoped<CorrelationIdMiddleware>();
builder.Services.AddScoped<RequestTimingMiddleware>();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
builder.Services.AddResponseCompression(o => { o.EnableForHttps = true; });
// Rate limiter
builder.Services.AddRateLimiter(o =>
{
o.AddFixedWindowLimiter("api", cfg => { cfg.PermitLimit = 100; cfg.Window = TimeSpan.FromMinutes(1); cfg.QueueLimit = 0; });
o.RejectionStatusCode = 429;
});
var app = builder.Build();
// ━━ Middleware order: ━━
// 1. Exception handler catches all downstream exceptions
app.UseExceptionHandler();
// 2. Security headers
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
app.UseHttpsRedirection();
// 3. Compression (before any content is written)
app.UseResponseCompression();
// 4. Custom cross-cutting concerns
app.UseMiddleware<RequestTimingMiddleware>();
app.UseMiddleware<CorrelationIdMiddleware>();
// 5. Routing infrastructure
app.UseRouting();
app.UseCors("ProductionPolicy");
// 6. Auth
app.UseAuthentication();
app.UseAuthorization();
// 7. Rate limiting (after auth - can limit by user ID)
app.UseRateLimiter();
// 8. Endpoints
app.MapControllers().RequireRateLimiting("api");
app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.Run();
// ━━ What this pipeline achieves ━━
// - Every request gets a correlation ID (traceable across services)
// - All requests are timed and logged with method/path/status/duration
// - Any unhandled exception → RFC 7807 ProblemDetails with status code mapping
// - HTTPS enforced in production, HSTS header added
// - Brotli/Gzip compression applied to JSON responses
// - 100 req/min rate limit per client
// - Auth enforced before rate limiting (authenticated users get proper limits)Tip
Tip
Practice Mini Project Request Logging Correlation Middleware in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Request Logging Correlation Middleware from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Mini Project Request Logging Correlation Middleware is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?