Request pipeline, built-in middleware, custom middleware & error handling
Muhammad Rizwan - rizwancode.com
var app = builder.Build();
app.UseExceptionHandler("/error"); // 1. Exception handling
app.UseHsts(); // 2. HSTS
app.UseHttpsRedirection(); // 3. HTTPS redirect
app.UseStaticFiles(); // 4. Static files
app.UseRouting(); // 5. Routing
app.UseCors(); // 6. CORS
app.UseAuthentication(); // 7. Auth
app.UseAuthorization(); // 8. Authz
app.UseRateLimiter(); // 9. Rate limiting
app.MapControllers(); // 10. Endpoints
// Use - calls next (middleware continues)
app.Use(async (context, next) =>
{
// Before the next middleware
context.Response.Headers.Append(
"X-Request-Id", Guid.NewGuid().ToString());
await next();
// After the next middleware
});
// Run - terminal (no next)
app.Run(async context =>
{
await context.Response
.WriteAsync("Terminal response");
});
// Map - branch pipeline by path
app.Map("/health", app =>
{
app.Run(async ctx =>
await ctx.Response.WriteAsync("OK"));
});
public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _log;
public RequestTimingMiddleware(
RequestDelegate next,
ILogger<RequestTimingMiddleware> log)
{
_next = next;
_log = log;
}
public async Task InvokeAsync(
HttpContext context)
{
var sw = Stopwatch.StartNew();
await _next(context);
sw.Stop();
_log.LogInformation(
"{Method} {Path} → {Status} in {Ms}ms",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode,
sw.ElapsedMilliseconds);
}
}
// Register
app.UseMiddleware<RequestTimingMiddleware>();
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
public GlobalExceptionMiddleware(
RequestDelegate next) => _next = next;
public async Task InvokeAsync(
HttpContext ctx)
{
try
{
await _next(ctx);
}
catch (Exception ex)
{
ctx.Response.StatusCode = 500;
ctx.Response.ContentType =
"application/problem+json";
await ctx.Response.WriteAsJsonAsync(
new {
Status = 500,
Title = "Internal Server Error",
Detail = ex.Message
});
}
}
}
| Middleware | Purpose |
|---|---|
UseExceptionHandler |
Global exception handling |
UseHsts |
HTTP Strict Transport Security |
UseHttpsRedirection |
Redirect HTTP → HTTPS |
UseStaticFiles |
Serve wwwroot files |
UseRouting |
Match routes to endpoints |
UseCors |
Cross-Origin Resource Sharing |
UseAuthentication |
Identify user |
UseAuthorization |
Enforce policies |
UseRateLimiter |
Rate limiting (.NET 7+) |
UseResponseCaching |
Cache responses |
UseResponseCompression |
Gzip/Brotli compression |
UseOutputCache |
Output caching (.NET 7+) |
// Only in development
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}
// MapWhen - branch by condition
app.MapWhen(
ctx => ctx.Request.Path
.StartsWithSegments("/api"),
apiApp =>
{
apiApp.UseMiddleware<ApiKeyMiddleware>();
});
// UseWhen - rejoin pipeline
app.UseWhen(
ctx => ctx.Request.Headers
.ContainsKey("X-Debug"),
app => app.UseMiddleware<DebugMiddleware>()
);
builder.Services.AddCors(o =>
{
o.AddPolicy("AllowFrontend", b => b
.WithOrigins("https://myapp.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
o.AddPolicy("AllowAll", b => b
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
app.UseCors("AllowFrontend");
// Per-endpoint
app.MapGet("/public", () => "hi")
.RequireCors("AllowAll");
builder.Services.AddRateLimiter(o =>
{
o.AddFixedWindowLimiter("fixed", opt =>
{
opt.PermitLimit = 10;
opt.Window = TimeSpan.FromMinutes(1);
opt.QueueLimit = 2;
});
o.AddSlidingWindowLimiter("sliding", opt =>
{
opt.PermitLimit = 100;
opt.Window = TimeSpan.FromMinutes(1);
opt.SegmentsPerWindow = 4;
});
});
app.UseRateLimiter();
app.MapGet("/api/data", () => "ok")
.RequireRateLimiting("fixed");