Need consistent request/response handling across all endpoints? Custom middleware creates reusable pipeline components.
Custom Middleware for Global Exception Handling:
// GlobalExceptionMiddleware.cs
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
private readonly IWebHostEnvironment _env;
public GlobalExceptionMiddleware(
RequestDelegate next,
ILogger logger,
IWebHostEnvironment env)
{
_next = next;
_logger = logger;
_env = env;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
_logger.LogError(exception, "Unhandled exception occurred");
context.Response.ContentType = "application/json";
var problemDetails = new ProblemDetails
{
Title = "An error occurred",
Status = GetStatusCode(exception),
Detail = _env.IsDevelopment() ? exception.Message : "An unexpected error occurred",
Instance = context.Request.Path,
Extensions = { ["traceId"] = context.TraceIdentifier }
};
if (_env.IsDevelopment())
{
problemDetails.Extensions["exception"] = new
{
exception.Message,
exception.StackTrace,
exception.Source,
InnerException = exception.InnerException?.Message
};
}
var json = JsonSerializer.Serialize(problemDetails, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = _env.IsDevelopment()
});
await context.Response.WriteAsync(json);
}
private static int GetStatusCode(Exception exception) =>
exception switch
{
ValidationException => StatusCodes.Status400BadRequest,
UnauthorizedAccessException => StatusCodes.Status401Unauthorized,
KeyNotFoundException => StatusCodes.Status404NotFound,
InvalidOperationException => StatusCodes.Status400BadRequest,
NotImplementedException => StatusCodes.Status501NotImplemented,
_ => StatusCodes.Status500InternalServerError
};
}
// Extension method for clean registration
public static class GlobalExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseGlobalExceptionHandler(
this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
// Program.cs usage
app.UseGlobalExceptionHandler();
// Place early in pipeline to catch all downstream exceptions
Request/Response Logging Middleware:
// RequestResponseLoggingMiddleware.cs
public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public RequestResponseLoggingMiddleware(
RequestDelegate next,
ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
// Log request
var request = await FormatRequest(context.Request);
_logger.LogInformation("Request: {Request}", request);
// Copy original response body stream
var originalBodyStream = context.Response.Body;
using var responseBody = new MemoryStream();
context.Response.Body = responseBody;
var stopwatch = Stopwatch.StartNew();
try
{
await _next(context);
stopwatch.Stop();
}
finally
{
// Log response
var response = await FormatResponse(context.Response);
_logger.LogInformation("Response: {Response} - Duration: {Duration}ms",
response, stopwatch.ElapsedMilliseconds);
// Copy the response back to original stream
responseBody.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalBodyStream);
}
}
private async Task FormatRequest(HttpRequest request)
{
request.EnableBuffering();
var body = await new StreamReader(request.Body)
.ReadToEndAsync();
request.Body.Position = 0;
var headers = request.Headers
.Where(h => !h.Key.StartsWith("Authorization"))
.ToDictionary(h => h.Key, h => h.Value.ToString());
return $"{request.Method} {request.Path}{request.QueryString} | " +
$"Headers: {JsonSerializer.Serialize(headers)} | " +
$"Body: {body}";
}
private async Task FormatResponse(HttpResponse response)
{
response.Body.Seek(0, SeekOrigin.Begin);
var body = await new StreamReader(response.Body)
.ReadToEndAsync();
response.Body.Position = 0;
return $"Status: {response.StatusCode} | " +
$"Headers: {JsonSerializer.Serialize(response.Headers)} | " +
$"Body: {body}";
}
}
// Advanced: Filter sensitive data
private string MaskSensitiveData(string input)
{
var patterns = new Dictionary
{
[@"password\":\s*"[^"]*""] = @""password": "***",
[@"token\":\s * "[^"] * ""] = @""token": " * **",
[@"creditCard\":\s * "[^"] * ""] = @""creditCard": " * **",
[@"ssn\":\s * "[^"] * ""] = @""ssn": " * **",
[@"Bearer\s + [\w\.-] + "] = @"Bearer * **"
};
foreach (var pattern in patterns)
{
input = Regex.Replace(input, pattern.Key, pattern.Value);
}
return input;
}
