first commit
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
using Serilog.Context;
|
||||
|
||||
namespace MyNewProjectName.AdminAPI.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware to generate and track correlation ID for each request
|
||||
/// This ID is added to HTTP headers and Serilog log context for easy tracing
|
||||
/// </summary>
|
||||
public class CorrelationIdMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private const string CorrelationIdHeaderName = "X-Correlation-ID";
|
||||
private const string CorrelationIdLogPropertyName = "CorrelationId";
|
||||
|
||||
public CorrelationIdMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
// Get correlation ID from request header, or generate a new one
|
||||
var correlationId = context.Request.Headers[CorrelationIdHeaderName].FirstOrDefault()
|
||||
?? $"req-{Guid.NewGuid():N}";
|
||||
|
||||
// Add correlation ID to response header
|
||||
context.Response.Headers[CorrelationIdHeaderName] = correlationId;
|
||||
|
||||
// Add correlation ID to Serilog log context
|
||||
// All logs within this request will automatically include this correlation ID
|
||||
using (LogContext.PushProperty(CorrelationIdLogPropertyName, correlationId))
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using MyNewProjectName.Contracts.DTOs.Responses;
|
||||
using MyNewProjectName.Domain.Exceptions;
|
||||
using Serilog;
|
||||
|
||||
namespace MyNewProjectName.AdminAPI.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Global exception handling middleware
|
||||
/// Catches all unhandled exceptions, logs them to Serilog with full details,
|
||||
/// and returns a standardized error response without exposing stack traces
|
||||
/// </summary>
|
||||
public class ExceptionHandlingMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly Serilog.ILogger _logger;
|
||||
|
||||
public ExceptionHandlingMiddleware(RequestDelegate next, Serilog.ILogger logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
// Get correlation ID from header (set by CorrelationIdMiddleware)
|
||||
var correlationId = context.Request.Headers["X-Correlation-ID"].FirstOrDefault() ?? "unknown";
|
||||
|
||||
// Log full exception details to Serilog (including stack trace)
|
||||
// This will be searchable by CorrelationId
|
||||
_logger.Error(
|
||||
exception,
|
||||
"Unhandled exception occurred. CorrelationId: {CorrelationId}, Path: {Path}, Method: {Method}",
|
||||
correlationId,
|
||||
context.Request.Path,
|
||||
context.Request.Method
|
||||
);
|
||||
|
||||
// Safety check: If response has already started, we cannot modify headers/status code
|
||||
// This prevents InvalidOperationException: "Headers are read-only, response has already started"
|
||||
if (context.Response.HasStarted)
|
||||
{
|
||||
_logger.Warning(
|
||||
"Response has already started. Cannot modify HTTP status code or headers. CorrelationId: {CorrelationId}",
|
||||
correlationId
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
var response = context.Response;
|
||||
|
||||
// Clear any existing response data
|
||||
response.Clear();
|
||||
|
||||
response.ContentType = "application/json";
|
||||
|
||||
// Determine status code and user-friendly message
|
||||
var (statusCode, message, errors) = exception switch
|
||||
{
|
||||
ValidationException validationEx => (
|
||||
HttpStatusCode.BadRequest,
|
||||
"Validation failed",
|
||||
validationEx.Errors.SelectMany(e => e.Value).ToList()),
|
||||
|
||||
NotFoundException => (
|
||||
HttpStatusCode.NotFound,
|
||||
exception.Message,
|
||||
new List<string>()),
|
||||
|
||||
DomainException => (
|
||||
HttpStatusCode.BadRequest,
|
||||
exception.Message,
|
||||
new List<string>()),
|
||||
|
||||
UnauthorizedAccessException => (
|
||||
HttpStatusCode.Unauthorized,
|
||||
"Unauthorized",
|
||||
new List<string>()),
|
||||
|
||||
_ => (
|
||||
HttpStatusCode.InternalServerError,
|
||||
"An error occurred while processing your request",
|
||||
new List<string>())
|
||||
};
|
||||
|
||||
response.StatusCode = (int)statusCode;
|
||||
|
||||
// Return standardized error response (NO stack trace exposed to client)
|
||||
var result = JsonSerializer.Serialize(new ApiResponse
|
||||
{
|
||||
Success = false,
|
||||
Message = message,
|
||||
Errors = errors.Any() ? errors : null
|
||||
}, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
});
|
||||
|
||||
await response.WriteAsync(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Serilog;
|
||||
|
||||
namespace MyNewProjectName.AdminAPI.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware to log request and response bodies
|
||||
/// WARNING: This can generate large log files. Use with caution in production.
|
||||
/// Consider enabling only for specific environments or endpoints.
|
||||
/// </summary>
|
||||
public class RequestResponseLoggingMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly Serilog.ILogger _logger;
|
||||
private readonly bool _enableRequestLogging;
|
||||
private readonly bool _enableResponseLogging;
|
||||
|
||||
// Paths that should NOT be logged (e.g., health checks, metrics)
|
||||
private static readonly string[] ExcludedPaths = new[]
|
||||
{
|
||||
"/health",
|
||||
"/metrics",
|
||||
"/favicon.ico"
|
||||
};
|
||||
|
||||
public RequestResponseLoggingMiddleware(
|
||||
RequestDelegate next,
|
||||
Serilog.ILogger logger,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
_enableRequestLogging = configuration.GetValue<bool>("Logging:EnableRequestLogging", false);
|
||||
_enableResponseLogging = configuration.GetValue<bool>("Logging:EnableResponseLogging", false);
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
// Skip logging for excluded paths
|
||||
if (ExcludedPaths.Any(path => context.Request.Path.StartsWithSegments(path)))
|
||||
{
|
||||
await _next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
var requestBody = string.Empty;
|
||||
var responseBody = string.Empty;
|
||||
|
||||
// Log request
|
||||
if (_enableRequestLogging)
|
||||
{
|
||||
requestBody = await ReadRequestBodyAsync(context.Request);
|
||||
_logger.Information(
|
||||
"Request: {Method} {Path} {QueryString} | Body: {RequestBody}",
|
||||
context.Request.Method,
|
||||
context.Request.Path,
|
||||
context.Request.QueryString,
|
||||
requestBody
|
||||
);
|
||||
}
|
||||
|
||||
// Capture response body
|
||||
var originalBodyStream = context.Response.Body;
|
||||
using var responseBodyStream = new MemoryStream();
|
||||
context.Response.Body = responseBodyStream;
|
||||
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
finally
|
||||
{
|
||||
stopwatch.Stop();
|
||||
|
||||
// Log response
|
||||
if (_enableResponseLogging)
|
||||
{
|
||||
responseBody = await ReadResponseBodyAsync(context.Response);
|
||||
await responseBodyStream.CopyToAsync(originalBodyStream);
|
||||
|
||||
_logger.Information(
|
||||
"Response: {StatusCode} | Duration: {Duration}ms | Body: {ResponseBody}",
|
||||
context.Response.StatusCode,
|
||||
stopwatch.ElapsedMilliseconds,
|
||||
responseBody
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
await responseBodyStream.CopyToAsync(originalBodyStream);
|
||||
}
|
||||
|
||||
context.Response.Body = originalBodyStream;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRequestBodyAsync(HttpRequest request)
|
||||
{
|
||||
// Enable buffering to allow reading the body multiple times
|
||||
request.EnableBuffering();
|
||||
|
||||
using var reader = new StreamReader(
|
||||
request.Body,
|
||||
encoding: Encoding.UTF8,
|
||||
detectEncodingFromByteOrderMarks: false,
|
||||
leaveOpen: true);
|
||||
|
||||
var body = await reader.ReadToEndAsync();
|
||||
request.Body.Position = 0; // Reset position for next middleware
|
||||
|
||||
// Truncate very long bodies to avoid huge logs
|
||||
return body.Length > 10000 ? body[..10000] + "... (truncated)" : body;
|
||||
}
|
||||
|
||||
private static async Task<string> ReadResponseBodyAsync(HttpResponse response)
|
||||
{
|
||||
response.Body.Seek(0, SeekOrigin.Begin);
|
||||
using var reader = new StreamReader(
|
||||
response.Body,
|
||||
encoding: Encoding.UTF8,
|
||||
detectEncodingFromByteOrderMarks: false,
|
||||
leaveOpen: true);
|
||||
|
||||
var body = await reader.ReadToEndAsync();
|
||||
response.Body.Seek(0, SeekOrigin.Begin); // Reset position
|
||||
|
||||
// Truncate very long bodies to avoid huge logs
|
||||
return body.Length > 10000 ? body[..10000] + "... (truncated)" : body;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user