Published on: June 5, 2025
Category: Real-World Use Case
Tags: ASP.NET Core, Middleware, .NET 8, Request Pipeline, Web API, Real World .NET, Coding Practices
🧱 What is Middleware in ASP.NET Core?
Middleware is code that:
- Handles an incoming HTTP request
- Can pass the request to the next component in the pipeline
- Optionally does something after the next component completes
📌 Real-World Scenario: Execution Time Logger Middleware
You want to log how long each request takes to execute — useful for performance monitoring.
🔧 Step-by-Step: Create the Middleware
✅ 1. Create a Middleware Class
public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var watch = Stopwatch.StartNew();
await _next(context);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
_logger.LogInformation($"Request took {elapsedMs} ms");
}
}
✅ 2. Register the Middleware in Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<RequestTimingMiddleware>();
app.MapControllers();
app.Run();
🧠 Best Practices for Custom Middleware
- Keep it small and single-responsibility
- Always call
_next(context)
or the pipeline breaks - Use
ILogger
instead ofConsole.WriteLine
- Avoid blocking operations; use
async/await
🔍 Other Real-World Use Cases:
- Add custom headers
- Request/response transformation
- IP whitelisting or filtering
- Audit logging
- API key validation
🧠 Pro Tip
To conditionally apply middleware only in development:
if (env.IsDevelopment())
{
app.UseMiddleware<SomeDebugMiddleware>();
}
📬 Stay Connected
- 🔗 Blog: www.ajaygangwar.com
- 💼 LinkedIn: Ajay Gangwar
- 📧 Email: seajaygangwar@gmail.com