
Middleware is an essential component of the ASP.NET request pipeline. It allows developers to run code during both the request and response lifecycle. In this article, we will explore what middleware is, and how it works, and provide real-world practical use cases with complete code examples.
What is Middleware in .NET?
Middleware in .NET is a software component that processes HTTP requests and responses. It is executed in a pipeline, where each middleware component can perform an action and decide whether to pass the request further or return a response.
Key Characteristics of Middleware
- Executes sequentially in the request pipeline.
- Can modify request and response objects.
- Can terminate request processing if needed.
- Supports dependency injection.
- Used for authentication, logging, rate limiting, and more.
How Middleware Works in .NET?
Middleware components are registered in the Program.cs file using the UseMiddleware<T>() method or inline with app.Use(). The middleware pipeline is executed in the order they are added.
- Receives an HttpContext
- Performs operations (e.g., logging, authentication, etc.)
- Calls the next middleware in the pipeline (or short-circuits the request)
Real-world middleware Use Cases with Code Examples
1. Request Logging Middleware
Use Case: Logging request and response details for debugging and monitoring.
Implementation
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
_logger.LogInformation($"Request: {context.Request.Method} {context.Request.Path}");
await _next(context);
}
}
Register the middleware as shown below.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<LoggingMiddleware>(); //register here!!
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello, Middleware!");
});
app.Run();
2. Custom Authentication Middleware
Use Case: Checking if a request contains a valid API key before processing.
Implementation
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private const string API_KEY = "123456"; // Hardcoded for demonstration
public ApiKeyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("X-API-KEY", out var extractedApiKey) || extractedApiKey != API_KEY)
{
context.Response.StatusCode = 401; // Unauthorized
await context.Response.WriteAsync("Invalid API Key.");
return;
}
await _next(context);
}
}
Register the middleware
app.UseMiddleware<ApiKeyMiddleware>();
3. Exception Handling Middleware
Use Case: Global error handling to return meaningful error responses.
Implementation
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "An unhandled exception occurred.");
context.Response.StatusCode = 500;
await context.Response.WriteAsync("An unexpected error occurred.");
}
}
}
Register the middleware.
app.UseMiddleware<ExceptionHandlingMiddleware>();
4. Rate Limiting Middleware
Use Case: Preventing abuse by limiting the number of requests from a client in a given time period.
Implementation
public class RateLimitingMiddleware
{
private static readonly Dictionary<string, (int Count, DateTime LastRequest)> _clients = new();
private readonly RequestDelegate _next;
private const int Limit = 5;
private static readonly TimeSpan TimeWindow = TimeSpan.FromMinutes(1);
public RateLimitingMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext context)
{
var clientIP = context.Connection.RemoteIpAddress?.ToString();
if (clientIP == null || !_clients.ContainsKey(clientIP) || DateTime.UtcNow - _clients[clientIP].LastRequest > TimeWindow)
_clients[clientIP] = (1, DateTime.UtcNow);
else if (_clients[clientIP].Count >= Limit)
{
context.Response.StatusCode = 429;
await context.Response.WriteAsync("Rate limit exceeded. Try again later.");
return;
}
else
_clients[clientIP] = (_clients[clientIP].Count + 1, DateTime.UtcNow);
await _next(context);
}
}
Register the middleware
app.UseMiddleware<RateLimitingMiddleware>();
5. Content Compression Middleware
Use Case: Compressing responses to improve performance.
We can use built-in Response Compression or custom Content Compression Middleware.
Implementation. built-in
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true; // Enable compression for HTTPS requests
options.Providers.Add<BrotliCompressionProvider>(); // Brotli compression
options.Providers.Add<GzipCompressionProvider>(); // Gzip compression
});
builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = System.IO.Compression.CompressionLevel.Fastest; // Adjust compression level
});
var app = builder.Build();
app.UseResponseCompression(); // Enable middleware
app.MapGet("/", async context =>
{
var responseText = new string('A', 1000); // Large response for compression testing
await context.Response.WriteAsync(responseText);
});
app.Run();
Join the conversation! Your thoughts help the community grow.