🔗 Middleware = Request Pipeline
Each request goes through pipeline. Middleware processes requests and responses. Logging, auth, error handling — all in pipeline.
📝 Basic Middleware
// Program.cs
var app = builder.Build();
// Built-in middleware
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Custom middleware (lambda)
app.Use(async (context, next) =>
{
Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");
await next();
Console.WriteLine($"Response: {context.Response.StatusCode}");
});
// Custom middleware (class)
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public RequestLoggingMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
// Before next middleware
_logger.LogInformation($"Request: {context.Request.Path} - {DateTime.Now}");
// Call next middleware
await _next(context);
// After next middleware
_logger.LogInformation($"Response: {context.Response.StatusCode}");
}
}
// Register middleware
app.UseMiddleware();
🎯 Common Middleware
# Error Handling
app.UseExceptionHandler("/Home/Error");
app.UseStatusCodePages();
# Exception handling (custom)
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync($"Error: {ex.Message} ");
}
});
# Request/Response Logging
public class RequestResponseMiddleware
{
private readonly RequestDelegate _next;
public async Task InvokeAsync(HttpContext context)
{
// Log request
context.Request.EnableBuffering();
var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
context.Request.Body.Position = 0;
// Call next
await _next(context);
// Log response
var responseBody = context.Response.Body.ToString();
}
}
# Authentication
app.UseAuthentication();
app.UseAuthorization();
# CORS
app.UseCors(policy => policy
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
# Compression
app.UseResponseCompression();
# Session
app.UseSession();
# Health Checks
app.UseHealthChecks("/health");
# Swagger
app.UseSwagger();
app.UseSwaggerUI();
✅ Middleware Order
- Exception/Error Handling (first)
- Static Files (early)
- Authentication/Authorization
- Logging (after auth)
- Custom Middleware
- Routing/Endpoints (last)
“Middleware handles requests in pipeline. Logging, auth, error handling — all organized. Essential for web apps.”

