Lesson 2 of 8
Custom Middleware - Conventional & IMiddleware
Custom middleware lets you inject cross-cutting concerns (logging, timing, security, correlation) into the pipeline without touching individual controllers. There are two patterns: conventional (class with RequestDelegate) and the IMiddleware interface (DI-friendly, preferred).
IMiddleware - DI-Friendly Approach
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
// ━━ IMiddleware - supports constructor DI directly ━━
// Register as Scoped - gets a fresh instance per request
public class CorrelationIdMiddleware(ILogger<CorrelationIdMiddleware> logger) : IMiddleware
{
private const string HeaderName = "X-Correlation-ID";
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
// 1. Get or generate correlation ID from request header
var correlationId = context.Request.Headers[HeaderName].FirstOrDefault()
?? Guid.NewGuid().ToString("N");
// 2. Store in HttpContext.Items for use anywhere in the request
context.Items["CorrelationId"] = correlationId;
// 3. Add to response so client can trace requests
context.Response.Headers[HeaderName] = correlationId;
// 4. Add to log scope - ALL logs within this request will include CorrelationId
using (logger.BeginScope(new Dictionary<string, object>
{ ["CorrelationId"] = correlationId }))
{
await next(context);
}
}
}
// ━━ Request timing middleware ━━
public class RequestTimingMiddleware(ILogger<RequestTimingMiddleware> logger) : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var method = context.Request.Method;
var path = context.Request.Path;
try
{
await next(context);
}
finally
{
sw.Stop();
var statusCode = context.Response.StatusCode;
var elapsed = sw.ElapsedMilliseconds;
// Use structured logging - not string interpolation
if (elapsed > 1000)
{
logger.LogWarning(
"SLOW REQUEST {Method} {Path} → {StatusCode} in {ElapsedMs}ms",
method, path, statusCode, elapsed);
}
else
{
logger.LogInformation(
"{Method} {Path} → {StatusCode} in {ElapsedMs}ms",
method, path, statusCode, elapsed);
}
}
}
}
// ━━ Registration ━━
// In DependencyInjection:
builder.Services.AddScoped<CorrelationIdMiddleware>();
builder.Services.AddScoped<RequestTimingMiddleware>();
// In middleware pipeline (order matters - timing wraps everything):
app.UseMiddleware<RequestTimingMiddleware>();
app.UseMiddleware<CorrelationIdMiddleware>();
// ━━ Extension method for cleaner Program.cs ━━
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseCorrelationId(this IApplicationBuilder app)
=> app.UseMiddleware<CorrelationIdMiddleware>();
public static IApplicationBuilder UseRequestTiming(this IApplicationBuilder app)
=> app.UseMiddleware<RequestTimingMiddleware>();
}
// Usage:
// app.UseRequestTiming();
// app.UseCorrelationId();Tip
Tip
Practice Custom Middleware Conventional IMiddleware 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 Custom Middleware Conventional IMiddleware 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.
Quick Quiz
Common Mistake
Warning
A common mistake with Custom Middleware Conventional IMiddleware 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?