From 146977c684011b72da27ad1891a4581233237e1c Mon Sep 17 00:00:00 2001 From: Cookies <11@22.com> Date: Sat, 20 Apr 2024 14:29:19 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E9=87=8D=E5=86=99=E4=BA=86=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=8F=82=E6=95=B0=E6=97=A5=E5=BF=97=E7=9A=84=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=EF=BC=8C=E5=8F=AF=E4=BB=A5=E6=AD=A3=E5=B8=B8=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E8=AF=B7=E6=B1=82=E5=92=8C=E8=BF=94=E5=9B=9E=E7=9A=84?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VOL.Core/Extensions/StringExtension.cs" | 7 ++- .../Middleware/ExceptionHandlerMiddleWare.cs" | 59 ++++++++++++------- .../VOL.Core/Extensions/StringExtension.cs | 6 ++ .../Middleware/ExceptionHandlerMiddleWare.cs | 58 ++++++++++++------ 4 files changed, 90 insertions(+), 40 deletions(-) diff --git "a/.Net6\347\211\210\346\234\254/VOL.Core/Extensions/StringExtension.cs" "b/.Net6\347\211\210\346\234\254/VOL.Core/Extensions/StringExtension.cs" index 8be7827bd..4a259f031 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.Core/Extensions/StringExtension.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.Core/Extensions/StringExtension.cs" @@ -577,6 +577,11 @@ public static string GenerateRandomNumber(this int length) } return newRandom.ToString(); } - + + public static string TruncateToLength(this string str, int maxLength = 1000) + { + if (string.IsNullOrEmpty(str)) return str; + return str.Length <= maxLength ? str : str.Substring(0, maxLength) + "..."; + } } } diff --git "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" index fa31cc305..fd96c1286 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" @@ -1,7 +1,5 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Hosting; using System; using System.IO; @@ -16,7 +14,6 @@ namespace VOL.Core.Middleware { - public class ExceptionHandlerMiddleWare { private readonly RequestDelegate next; @@ -27,31 +24,53 @@ public ExceptionHandlerMiddleWare(RequestDelegate next) public async Task Invoke(HttpContext context) { + context.Request.EnableBuffering(); + + var requestBodyStream = new MemoryStream(); + await context.Request.Body.CopyToAsync(requestBodyStream); + requestBodyStream.Seek(0, SeekOrigin.Begin); + + var requestBodyText = new StreamReader(requestBodyStream).ReadToEnd(); + + // Get the URL parameters + var urlParameters = context.Request.Query; + if (urlParameters.Count > 0) + { + requestBodyText = "URL Parameters: " + urlParameters + Environment.NewLine + requestBodyText; + } + + requestBodyStream.Seek(0, SeekOrigin.Begin); + context.Request.Body = requestBodyStream; + + // Create a new memory stream + var originalBodyStream = context.Response.Body; try { - context.Request.EnableBuffering(); - (context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now; - await next(context); - //app.UseMiddleware()放在 app.UseRouting()后才可以在await next(context);前执行 - Endpoint endpoint = context.Features.Get()?.Endpoint; - if (endpoint != null && endpoint is RouteEndpoint routeEndpoint) + using (var responseBody = new MemoryStream()) { - ActionLog log = endpoint.Metadata.GetMetadata(); - if (log != null && log.Write) - { - Logger.Add(log?.LogType, null, null, null, status: LoggerStatus.Info); - } - } - else - { - Logger.Info(LoggerType.Info); + // Replace the context response body with our memory stream + context.Response.Body = responseBody; + + (context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now; + // Continue down the Middleware pipeline + await next(context); + + // Copy the contents of the new memory stream (which contains the response) to the original stream + responseBody.Seek(0, SeekOrigin.Begin); + var responseBodyText = new StreamReader(responseBody).ReadToEnd(); + + Logger.Info(LoggerType.System, requestBodyText.TruncateToLength(), responseBodyText.TruncateToLength()); + + + responseBody.Seek(0, SeekOrigin.Begin); + await responseBody.CopyToAsync(originalBodyStream); } } catch (Exception exception) { var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; - string message = exception.Message + exception.StackTrace + exception.InnerException; - Logger.Error(LoggerType.Exception, message); + string message = exception.Message + exception.InnerException; + Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message); if (!env.IsDevelopment()) { message = "服务器处理异常"; diff --git a/Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs b/Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs index 8be7827bd..1972903df 100644 --- a/Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs +++ b/Net6.SqlSugar/VOL.Core/Extensions/StringExtension.cs @@ -578,5 +578,11 @@ public static string GenerateRandomNumber(this int length) return newRandom.ToString(); } + public static string TruncateToLength(this string str, int maxLength = 1000) + { + if (string.IsNullOrEmpty(str)) return str; + return str.Length <= maxLength ? str : str.Substring(0, maxLength) + "..."; + } + } } diff --git a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs index bc949f142..fd96c1286 100644 --- a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs +++ b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs @@ -1,13 +1,12 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Hosting; using System; using System.IO; using System.Text; using System.Threading.Tasks; using VOL.Core.Const; +using VOL.Core.EFDbContext; using VOL.Core.Enums; using VOL.Core.Extensions; using VOL.Core.ManageUser; @@ -15,7 +14,6 @@ namespace VOL.Core.Middleware { - public class ExceptionHandlerMiddleWare { private readonly RequestDelegate next; @@ -26,31 +24,53 @@ public ExceptionHandlerMiddleWare(RequestDelegate next) public async Task Invoke(HttpContext context) { + context.Request.EnableBuffering(); + + var requestBodyStream = new MemoryStream(); + await context.Request.Body.CopyToAsync(requestBodyStream); + requestBodyStream.Seek(0, SeekOrigin.Begin); + + var requestBodyText = new StreamReader(requestBodyStream).ReadToEnd(); + + // Get the URL parameters + var urlParameters = context.Request.Query; + if (urlParameters.Count > 0) + { + requestBodyText = "URL Parameters: " + urlParameters + Environment.NewLine + requestBodyText; + } + + requestBodyStream.Seek(0, SeekOrigin.Begin); + context.Request.Body = requestBodyStream; + + // Create a new memory stream + var originalBodyStream = context.Response.Body; try { - context.Request.EnableBuffering(); - (context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now; - await next(context); - //app.UseMiddleware()放在 app.UseRouting()后才可以在await next(context);前执行 - Endpoint endpoint = context.Features.Get()?.Endpoint; - if (endpoint != null && endpoint is RouteEndpoint routeEndpoint) + using (var responseBody = new MemoryStream()) { - ActionLog log = endpoint.Metadata.GetMetadata(); - if (log != null && log.Write) - { - Logger.Add(log?.LogType, null, null, null, status: LoggerStatus.Info); - } - } - else - { - Logger.Info(LoggerType.Info); + // Replace the context response body with our memory stream + context.Response.Body = responseBody; + + (context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now; + // Continue down the Middleware pipeline + await next(context); + + // Copy the contents of the new memory stream (which contains the response) to the original stream + responseBody.Seek(0, SeekOrigin.Begin); + var responseBodyText = new StreamReader(responseBody).ReadToEnd(); + + Logger.Info(LoggerType.System, requestBodyText.TruncateToLength(), responseBodyText.TruncateToLength()); + + + responseBody.Seek(0, SeekOrigin.Begin); + await responseBody.CopyToAsync(originalBodyStream); } } catch (Exception exception) { var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; string message = exception.Message + exception.InnerException; - Logger.Error(LoggerType.Exception, message); + Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message); if (!env.IsDevelopment()) { message = "服务器处理异常"; From 8bc531ea1665eb4a55c33bc2030fcdb8f8231671 Mon Sep 17 00:00:00 2001 From: Cookies <11@22.com> Date: Sat, 20 Apr 2024 14:40:14 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E4=B8=8D=E5=BF=85=E8=A6=81=E7=9A=84=E5=BC=95=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" | 2 -- Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs | 2 -- 2 files changed, 4 deletions(-) diff --git "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" index fd96c1286..5a2c840d7 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" @@ -6,10 +6,8 @@ using System.Text; using System.Threading.Tasks; using VOL.Core.Const; -using VOL.Core.EFDbContext; using VOL.Core.Enums; using VOL.Core.Extensions; -using VOL.Core.ManageUser; using VOL.Core.Services; namespace VOL.Core.Middleware diff --git a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs index fd96c1286..5a2c840d7 100644 --- a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs +++ b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs @@ -6,10 +6,8 @@ using System.Text; using System.Threading.Tasks; using VOL.Core.Const; -using VOL.Core.EFDbContext; using VOL.Core.Enums; using VOL.Core.Extensions; -using VOL.Core.ManageUser; using VOL.Core.Services; namespace VOL.Core.Middleware From de00455b8b11c24707787b3b769d7fda17ed1d2c Mon Sep 17 00:00:00 2001 From: Cookies <11@22.com> Date: Sat, 20 Apr 2024 18:53:15 +0800 Subject: [PATCH 3/6] =?UTF-8?q?url=E5=8F=82=E6=95=B0=E6=9C=AA=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E5=8C=96=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" | 4 +++- .../VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" index 5a2c840d7..f6f55389c 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" @@ -3,6 +3,7 @@ using Microsoft.Extensions.Hosting; using System; using System.IO; +using System.Linq; using System.Text; using System.Threading.Tasks; using VOL.Core.Const; @@ -34,7 +35,8 @@ public async Task Invoke(HttpContext context) var urlParameters = context.Request.Query; if (urlParameters.Count > 0) { - requestBodyText = "URL Parameters: " + urlParameters + Environment.NewLine + requestBodyText; + var formattedParameters = string.Join("&", urlParameters.Select(x => $"{x.Key}={x.Value}")); + requestBodyText = "URL 参数: " + formattedParameters + Environment.NewLine + requestBodyText; } requestBodyStream.Seek(0, SeekOrigin.Begin); diff --git a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs index 5a2c840d7..f6f55389c 100644 --- a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs +++ b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Hosting; using System; using System.IO; +using System.Linq; using System.Text; using System.Threading.Tasks; using VOL.Core.Const; @@ -34,7 +35,8 @@ public async Task Invoke(HttpContext context) var urlParameters = context.Request.Query; if (urlParameters.Count > 0) { - requestBodyText = "URL Parameters: " + urlParameters + Environment.NewLine + requestBodyText; + var formattedParameters = string.Join("&", urlParameters.Select(x => $"{x.Key}={x.Value}")); + requestBodyText = "URL 参数: " + formattedParameters + Environment.NewLine + requestBodyText; } requestBodyStream.Seek(0, SeekOrigin.Begin); From ebb695f66fb96aa7fa2a1b30908d20027a4ae7b3 Mon Sep 17 00:00:00 2001 From: Cookies <11@22.com> Date: Sat, 20 Apr 2024 19:11:50 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E9=9D=99=E6=80=81=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E4=B8=8D=E8=AE=B0=E5=BD=95=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ".Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" | 2 +- Net6.SqlSugar/VOL.WebApi/Startup.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git "a/.Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" "b/.Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" index 94cd1b97f..0a11102d6 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.WebApi/Startup.cs" @@ -216,12 +216,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseQuartz(env); } - app.UseMiddleware(); app.UseDefaultFiles(); app.UseStaticFiles().UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); + app.UseMiddleware(); app.Use(HttpRequestMiddleware.Context); //2021.06.27增加创建默认upload文件夹 diff --git a/Net6.SqlSugar/VOL.WebApi/Startup.cs b/Net6.SqlSugar/VOL.WebApi/Startup.cs index d6d20b109..cbda5c381 100644 --- a/Net6.SqlSugar/VOL.WebApi/Startup.cs +++ b/Net6.SqlSugar/VOL.WebApi/Startup.cs @@ -220,12 +220,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseQuartz(env); } - app.UseMiddleware(); app.UseDefaultFiles(); app.UseStaticFiles().UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); + app.UseMiddleware(); app.Use(HttpRequestMiddleware.Context); //2021.06.27增加创建默认upload文件夹 From 256f7d3ed793954231f5e28ffe21cdcae8fbf9c7 Mon Sep 17 00:00:00 2001 From: Cookies <11@22.com> Date: Sat, 20 Apr 2024 22:35:50 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dsqlsugar=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E6=B2=A1=E6=9C=89=E7=BB=9F=E8=AE=A1=E6=97=B6=E9=95=BF?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Net6.SqlSugar/VOL.Core/Services/Logger.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Net6.SqlSugar/VOL.Core/Services/Logger.cs b/Net6.SqlSugar/VOL.Core/Services/Logger.cs index 898a30c09..9bf70bdd1 100644 --- a/Net6.SqlSugar/VOL.Core/Services/Logger.cs +++ b/Net6.SqlSugar/VOL.Core/Services/Logger.cs @@ -168,6 +168,10 @@ private static void Start() if (loggerQueueData.Count() > 0 && list.Count < 500) { loggerQueueData.TryDequeue(out Sys_Log log); + if (log.EndDate != null && log.BeginDate != null) + { + log.ElapsedTime = (int)(((DateTime)log.EndDate - (DateTime)log.BeginDate).TotalMilliseconds); + } list.Add(log); continue; } From 286c344df0dd13d283e1a8b1314f8ce126874fda Mon Sep 17 00:00:00 2001 From: Cookies <11@22.com> Date: Wed, 1 May 2024 00:06:24 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dusing=E8=8C=83=E5=9B=B4?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Middleware/ExceptionHandlerMiddleWare.cs" | 34 ++++---- .../Middleware/ExceptionHandlerMiddleWare.cs | 34 ++++---- .../Middleware/ExceptionHandlerMiddleWare.cs" | 87 +++++++++++-------- 3 files changed, 87 insertions(+), 68 deletions(-) diff --git "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" index f6f55389c..1a7419173 100644 --- "a/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" +++ "b/.Net6\347\211\210\346\234\254/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" @@ -44,9 +44,9 @@ public async Task Invoke(HttpContext context) // Create a new memory stream var originalBodyStream = context.Response.Body; - try + using (var responseBody = new MemoryStream()) { - using (var responseBody = new MemoryStream()) + try { // Replace the context response body with our memory stream context.Response.Body = responseBody; @@ -65,23 +65,23 @@ public async Task Invoke(HttpContext context) responseBody.Seek(0, SeekOrigin.Begin); await responseBody.CopyToAsync(originalBodyStream); } - } - catch (Exception exception) - { - var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; - string message = exception.Message + exception.InnerException; - Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message); - if (!env.IsDevelopment()) - { - message = "服务器处理异常"; - } - else + catch (Exception exception) { - Console.WriteLine($"服务器处理出现异常:{message}"); + var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; + string message = exception.Message + exception.InnerException; + Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message); + if (!env.IsDevelopment()) + { + message = "服务器处理异常"; + } + else + { + Console.WriteLine($"服务器处理出现异常:{message}"); + } + context.Response.StatusCode = 500; + context.Response.ContentType = ApplicationContentType.JSON; + await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8); } - context.Response.StatusCode = 500; - context.Response.ContentType = ApplicationContentType.JSON; - await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8); } } } diff --git a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs index f6f55389c..1a7419173 100644 --- a/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs +++ b/Net6.SqlSugar/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs @@ -44,9 +44,9 @@ public async Task Invoke(HttpContext context) // Create a new memory stream var originalBodyStream = context.Response.Body; - try + using (var responseBody = new MemoryStream()) { - using (var responseBody = new MemoryStream()) + try { // Replace the context response body with our memory stream context.Response.Body = responseBody; @@ -65,23 +65,23 @@ public async Task Invoke(HttpContext context) responseBody.Seek(0, SeekOrigin.Begin); await responseBody.CopyToAsync(originalBodyStream); } - } - catch (Exception exception) - { - var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; - string message = exception.Message + exception.InnerException; - Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message); - if (!env.IsDevelopment()) - { - message = "服务器处理异常"; - } - else + catch (Exception exception) { - Console.WriteLine($"服务器处理出现异常:{message}"); + var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; + string message = exception.Message + exception.InnerException; + Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message); + if (!env.IsDevelopment()) + { + message = "服务器处理异常"; + } + else + { + Console.WriteLine($"服务器处理出现异常:{message}"); + } + context.Response.StatusCode = 500; + context.Response.ContentType = ApplicationContentType.JSON; + await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8); } - context.Response.StatusCode = 500; - context.Response.ContentType = ApplicationContentType.JSON; - await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8); } } } diff --git "a/\345\274\200\345\217\221\347\211\210dev/Net6\345\274\200\345\217\221\347\211\210/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" "b/\345\274\200\345\217\221\347\211\210dev/Net6\345\274\200\345\217\221\347\211\210/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" index fa31cc305..1a7419173 100644 --- "a/\345\274\200\345\217\221\347\211\210dev/Net6\345\274\200\345\217\221\347\211\210/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" +++ "b/\345\274\200\345\217\221\347\211\210dev/Net6\345\274\200\345\217\221\347\211\210/VOL.Core/Middleware/ExceptionHandlerMiddleWare.cs" @@ -1,22 +1,18 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Hosting; using System; using System.IO; +using System.Linq; using System.Text; using System.Threading.Tasks; using VOL.Core.Const; -using VOL.Core.EFDbContext; using VOL.Core.Enums; using VOL.Core.Extensions; -using VOL.Core.ManageUser; using VOL.Core.Services; namespace VOL.Core.Middleware { - public class ExceptionHandlerMiddleWare { private readonly RequestDelegate next; @@ -27,42 +23,65 @@ public ExceptionHandlerMiddleWare(RequestDelegate next) public async Task Invoke(HttpContext context) { - try + context.Request.EnableBuffering(); + + var requestBodyStream = new MemoryStream(); + await context.Request.Body.CopyToAsync(requestBodyStream); + requestBodyStream.Seek(0, SeekOrigin.Begin); + + var requestBodyText = new StreamReader(requestBodyStream).ReadToEnd(); + + // Get the URL parameters + var urlParameters = context.Request.Query; + if (urlParameters.Count > 0) { - context.Request.EnableBuffering(); - (context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now; - await next(context); - //app.UseMiddleware()放在 app.UseRouting()后才可以在await next(context);前执行 - Endpoint endpoint = context.Features.Get()?.Endpoint; - if (endpoint != null && endpoint is RouteEndpoint routeEndpoint) - { - ActionLog log = endpoint.Metadata.GetMetadata(); - if (log != null && log.Write) - { - Logger.Add(log?.LogType, null, null, null, status: LoggerStatus.Info); - } - } - else - { - Logger.Info(LoggerType.Info); - } + var formattedParameters = string.Join("&", urlParameters.Select(x => $"{x.Key}={x.Value}")); + requestBodyText = "URL 参数: " + formattedParameters + Environment.NewLine + requestBodyText; } - catch (Exception exception) + + requestBodyStream.Seek(0, SeekOrigin.Begin); + context.Request.Body = requestBodyStream; + + // Create a new memory stream + var originalBodyStream = context.Response.Body; + using (var responseBody = new MemoryStream()) { - var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; - string message = exception.Message + exception.StackTrace + exception.InnerException; - Logger.Error(LoggerType.Exception, message); - if (!env.IsDevelopment()) + try { - message = "服务器处理异常"; + // Replace the context response body with our memory stream + context.Response.Body = responseBody; + + (context.RequestServices.GetService(typeof(ActionObserver)) as ActionObserver).RequestDate = DateTime.Now; + // Continue down the Middleware pipeline + await next(context); + + // Copy the contents of the new memory stream (which contains the response) to the original stream + responseBody.Seek(0, SeekOrigin.Begin); + var responseBodyText = new StreamReader(responseBody).ReadToEnd(); + + Logger.Info(LoggerType.System, requestBodyText.TruncateToLength(), responseBodyText.TruncateToLength()); + + + responseBody.Seek(0, SeekOrigin.Begin); + await responseBody.CopyToAsync(originalBodyStream); } - else + catch (Exception exception) { - Console.WriteLine($"服务器处理出现异常:{message}"); + var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; + string message = exception.Message + exception.InnerException; + Logger.Error(LoggerType.Exception, requestBodyText.TruncateToLength(), "", message); + if (!env.IsDevelopment()) + { + message = "服务器处理异常"; + } + else + { + Console.WriteLine($"服务器处理出现异常:{message}"); + } + context.Response.StatusCode = 500; + context.Response.ContentType = ApplicationContentType.JSON; + await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8); } - context.Response.StatusCode = 500; - context.Response.ContentType = ApplicationContentType.JSON; - await context.Response.WriteAsync(new { message, status = false }.Serialize(), Encoding.UTF8); } } }