Custom Middleware & Error Handling

Custom Middleware & Error Handling in .NET: Middleware components form a bidirectional pipeline around every incoming HTTP request and outgoing HTTP response.

Middleware components form a bidirectional pipeline around every incoming HTTP request and outgoing HTTP response.


1. Building a Custom Performance Logging Middleware

public class PerformanceTrackerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<PerformanceTrackerMiddleware> _logger;

    public PerformanceTrackerMiddleware(RequestDelegate next, ILogger<PerformanceTrackerMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var stopwatch = System.Diagnostics.Stopwatch.StartNew();
        
        try
        {
            // Execute the next middleware down the pipeline
            await _next(context);
        }
        finally
        {
            stopwatch.Stop();
            var elapsedMs = stopwatch.ElapsedMilliseconds;

            if (elapsedMs > 500)
            {
                _logger.LogWarning(
                    "Slow HTTP Request: {Method} {Path} took {ElapsedMs}ms",
                    context.Request.Method,
                    context.Request.Path,
                    elapsedMs
                );
            }
        }
    }
}

// Extension method for clean Program.cs syntax
public static class PerformanceMiddlewareExtensions
{
    public static IApplicationBuilder UsePerformanceTracker(this IApplicationBuilder app)
        => app.UseMiddleware<PerformanceTrackerMiddleware>();
}

2. Using Modern .NET 8 IExceptionHandler

In .NET 8, rather than writing custom middleware from scratch for unhandled exceptions, implement the standardized IExceptionHandler interface:

public class GlobalExceptionHandler : IExceptionHandler
{
    private readonly ILogger<GlobalExceptionHandler> _logger;

    public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
    {
        _logger = logger;
    }

    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext, 
        Exception exception, 
        CancellationToken cancellationToken)
    {
        _logger.LogError(exception, "Unhandled system exception: {Message}", exception.Message);

        var problemDetails = new ProblemDetails
        {
            Status = StatusCodes.Status500InternalServerError,
            Title = "An unexpected server error occurred.",
            Detail = exception.Message,
            Instance = httpContext.Request.Path
        };

        httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
        await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);

        return true; // Indicates exception was handled
    }
}