Http進來的資料和出去的資料都記錄在log中
public class HttpLoggingMiddleware { private readonly RequestDelegate _next; private readonly ILogger<HttpLoggingMiddleware> _logger; public HttpLoggingMiddleware(RequestDelegate next, ILogger<HttpLoggingMiddleware> logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { // 記錄請求資訊 var request = context.Request; var requestLog = new StringBuilder(); requestLog.AppendLine("HTTP Request Information:"); requestLog.AppendLine($"Method: {request.Method}"); requestLog.AppendLine($"Path: {request.Path}"); requestLog.AppendLine("Headers:"); foreach (var header in request.Headers) { requestLog.AppendLine($"{header.Key}: {header.Value}"); } requestLog.AppendLine("Query Parameters:"); foreach (var param in request.Query) { requestLog.AppendLine($"{param.Key}: {param.Value}"); } if (request.ContentLength > 0) { request.EnableBuffering(); using (var reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true)) { var body = await reader.ReadToEndAsync(); requestLog.AppendLine($"Body: {body}"); request.Body.Position = 0; } } _logger.LogInformation(requestLog.ToString()); // 記錄響應資訊 var originalBodyStream = context.Response.Body; using (var responseBody = new MemoryStream()) { context.Response.Body = responseBody; await _next(context); context.Response.Body.Seek(0, SeekOrigin.Begin); var responseText = await new StreamReader(context.Response.Body).ReadToEndAsync(); context.Response.Body.Seek(0, SeekOrigin.Begin); if (context.Response.ContentType != null && context.Response.ContentType.Contains("application/json")) { var responseLog = new StringBuilder(); responseLog.AppendLine("HTTP Response Information:"); responseLog.AppendLine($"Status Code: {context.Response.StatusCode}"); responseLog.AppendLine("Headers:"); foreach (var header in context.Response.Headers) { responseLog.AppendLine($"{header.Key}: {header.Value}"); } responseLog.AppendLine($"Body: {responseText}"); _logger.LogInformation(responseLog.ToString()); } await responseBody.CopyToAsync(originalBodyStream); } } }
app.UseMiddleware<HttpLoggingMiddleware>();