From bfd8c703c9a8af67f22e378a1f5424cab1ad07b5 Mon Sep 17 00:00:00 2001 From: zhangxiaofeng Date: Fri, 5 Apr 2024 18:29:17 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/OrderController.cs | 6 - EntrustSettle.Api/Program.cs | 8 -- EntrustSettle.Api/appsettings.Staging.json | 10 -- EntrustSettle.Api/appsettings.json | 12 +- EntrustSettle.Common/LogHelper/LogLock.cs | 7 - EntrustSettle.Extensions/AOP/SqlsugarAop.cs | 13 +- .../Policys/PermissionHandler.cs | 7 +- .../Middlewares/IpLogMiddleware.cs | 127 ------------------ .../Middlewares/MiddlewareHelpers.cs | 10 -- .../Middlewares/RecordAccessLogsMiddleware.cs | 13 +- .../Middlewares/RequRespLogMiddleware.cs | 6 +- .../ServiceExtensions/AppConfigSetup.cs | 5 +- .../ServiceExtensions/SqlsugarSetup.cs | 6 +- 13 files changed, 31 insertions(+), 199 deletions(-) delete mode 100644 EntrustSettle.Extensions/Middlewares/IpLogMiddleware.cs diff --git a/EntrustSettle.Api/Controllers/OrderController.cs b/EntrustSettle.Api/Controllers/OrderController.cs index ce2f7fb..703ae00 100644 --- a/EntrustSettle.Api/Controllers/OrderController.cs +++ b/EntrustSettle.Api/Controllers/OrderController.cs @@ -3,7 +3,6 @@ using EntrustSettle.Common.Const; using EntrustSettle.Common.Extensions; using EntrustSettle.Common.Helper; using EntrustSettle.Controllers; -using EntrustSettle.IRepository.Base; using EntrustSettle.IServices; using EntrustSettle.IServices.Base; using EntrustSettle.Model; @@ -12,14 +11,9 @@ using EntrustSettle.Model.Models; using EntrustSettle.Model.Models.DJY; using EntrustSettle.Model.Validator; using EntrustSettle.Repository.UnitOfWorks; -using EntrustSettle.Services.Base; using FluentValidation; -using Mapster; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; -using RabbitMQ.Client; -using System.Text; namespace EntrustSettle.Api.Controllers { diff --git a/EntrustSettle.Api/Program.cs b/EntrustSettle.Api/Program.cs index e8e3406..177f7fc 100644 --- a/EntrustSettle.Api/Program.cs +++ b/EntrustSettle.Api/Program.cs @@ -176,7 +176,6 @@ internal class Program app.UseRequestResponseLogMiddle(); // 请求响应日志 app.UseRecordAccessLogsMiddle(); // 记录访问日志 app.UseSignalRSendMiddle(); // SignalR发送消息 - app.UseIpLogMiddle(); // IP记录 app.UseAllServicesMiddle(builder.Services); // 查看所有注入的服务 app.UseSession(); @@ -214,13 +213,6 @@ internal class Program // 这种自定义授权中间件,可以尝试,但不推荐 // app.UseJwtTokenAuth(); - // 测试用户,用来通过鉴权 - //if (builder.Configuration.GetValue("AppSettings:UseLoadTest")) - //{ - // app.UseMiddleware(); - //} - - app.UseAuthentication(); // 认证中间件 app.UseAuthorization(); // 授权中间件 diff --git a/EntrustSettle.Api/appsettings.Staging.json b/EntrustSettle.Api/appsettings.Staging.json index 7d6a15c..13e21a8 100644 --- a/EntrustSettle.Api/appsettings.Staging.json +++ b/EntrustSettle.Api/appsettings.Staging.json @@ -55,15 +55,6 @@ "Enabled": false } }, - "IPLog": { - "Enabled": false, - "LogToFile": { - "Enabled": false - }, - "LogToDB": { - "Enabled": false - } - }, "RecordAccessLogs": { "Enabled": false, "LogToFile": { @@ -136,7 +127,6 @@ }, "SeedDBEnabled": false, //生成表结构 "RoutePrefix": "", //路由变量前缀配置 - "UseLoadTest": false }, // DBType对应:0=MySql,1=SqlServer,2=Sqlite,3=Oracle,4=PostgreSQL,5=Dm,6=Kdbndp // diff --git a/EntrustSettle.Api/appsettings.json b/EntrustSettle.Api/appsettings.json index 19ffc25..281da89 100644 --- a/EntrustSettle.Api/appsettings.json +++ b/EntrustSettle.Api/appsettings.json @@ -55,15 +55,6 @@ "Enabled": false } }, - "IPLog": { - "Enabled": true, - "LogToFile": { - "Enabled": true - }, - "LogToDB": { - "Enabled": false - } - }, "RecordAccessLogs": { "Enabled": true, "LogToFile": { @@ -136,7 +127,6 @@ }, "SeedDBEnabled": false, //生成表结构 "RoutePrefix": "", //路由变量前缀配置 - "UseLoadTest": false }, // DBType对应:0=MySql,1=SqlServer,2=Sqlite,3=Oracle,4=PostgreSQL,5=Dm,6=Kdbndp // @@ -239,7 +229,7 @@ "Enabled": false }, "Redis": { - "Enabled": true, + "Enabled": false, "ConnectionString": "127.0.0.1:6379,defaultDatabase=3", "InstanceName": "" //Key前缀 }, diff --git a/EntrustSettle.Common/LogHelper/LogLock.cs b/EntrustSettle.Common/LogHelper/LogLock.cs index cb3d551..f4c2958 100644 --- a/EntrustSettle.Common/LogHelper/LogLock.cs +++ b/EntrustSettle.Common/LogHelper/LogLock.cs @@ -34,10 +34,6 @@ namespace EntrustSettle.Common.LogHelper break; // 中间件中使用 - case "RequestIpInfoLog": - AppSetingNodeName = "Middleware"; - AppSetingName = "IPLog"; - break; case "RecordAccessLogs": AppSetingNodeName = "Middleware"; AppSetingName = "RecordAccessLogs"; @@ -187,9 +183,6 @@ namespace EntrustSettle.Common.LogHelper case "ServiceAOPLogEx": logger.Error(logContent); break; - case "RequestIpInfoLog": - logger.Info(logContent); - break; case "RecordAccessLogs": logger.Info(logContent); break; diff --git a/EntrustSettle.Extensions/AOP/SqlsugarAop.cs b/EntrustSettle.Extensions/AOP/SqlsugarAop.cs index b492a34..4e41d9d 100644 --- a/EntrustSettle.Extensions/AOP/SqlsugarAop.cs +++ b/EntrustSettle.Extensions/AOP/SqlsugarAop.cs @@ -9,7 +9,7 @@ namespace EntrustSettle.Common.DB.Aop; public static class SqlSugarAop { - public static void OnLogExecuting(string sql, SugarParameter[] p, string user) + public static void OnLogExecuting(string sql, SugarParameter[] param, string path, string user, string traceId) { if (AppSettings.app(new string[] { "AppSettings", "SqlAOPLog", "Enabled" }).ObjToBool()) { @@ -18,11 +18,12 @@ public static class SqlSugarAop Parallel.For(0, 1, e => { // 完整sql语句 - LogLock.OutLogAOP("SqlAOPLog", "", + LogLock.OutLogAOP("SqlAOPLog", traceId, [ - $"【操作人】:{user}", - "【SQL语句】:", - GetWholeSql(p, sql), + $"[Path]:{path}", + $"[User]:{user}", + "[SQL]:", + GetWholeSql(param, sql), ]); // 参数化sql语句 //LogLock.OutLogAOP("SqlAOPLog", "", new string[] { GetParas(p), "【SQL语句】:" + sql }); @@ -30,7 +31,7 @@ public static class SqlSugarAop } if (AppSettings.app(new string[] { "AppSettings", "SqlAOPLog", "LogToConsole", "Enabled" }).ObjToBool()) { - ConsoleHelper.WriteColorLine(string.Join("\r\n", new string[] { "--------", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} :" + GetWholeSql(p, sql) }), ConsoleColor.DarkCyan); + ConsoleHelper.WriteColorLine(string.Join("\r\n", new string[] { "--------", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} :" + GetWholeSql(param, sql) }), ConsoleColor.DarkCyan); } } } diff --git a/EntrustSettle.Extensions/Authorizations/Policys/PermissionHandler.cs b/EntrustSettle.Extensions/Authorizations/Policys/PermissionHandler.cs index 540f7e8..8ed6176 100644 --- a/EntrustSettle.Extensions/Authorizations/Policys/PermissionHandler.cs +++ b/EntrustSettle.Extensions/Authorizations/Policys/PermissionHandler.cs @@ -124,14 +124,9 @@ namespace EntrustSettle.AuthHelper { var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name); - // 是否开启测试环境 - var isTestCurrent = AppSettings.app(new string[] { "AppSettings", "UseLoadTest" }).ObjToBool(); - //result?.Principal不为空即登录成功 - if (result?.Principal != null || isTestCurrent || httpContext.IsSuccessSwagger()) + if (result?.Principal != null || httpContext.IsSuccessSwagger()) { - if (!isTestCurrent) httpContext.User = result.Principal; - //应该要先校验用户的信息 再校验菜单权限相关的 // JWT模式下校验当前用户状态 // IDS4也可以校验,可以通过服务或者接口形式 diff --git a/EntrustSettle.Extensions/Middlewares/IpLogMiddleware.cs b/EntrustSettle.Extensions/Middlewares/IpLogMiddleware.cs deleted file mode 100644 index bbfc4e8..0000000 --- a/EntrustSettle.Extensions/Middlewares/IpLogMiddleware.cs +++ /dev/null @@ -1,127 +0,0 @@ -using EntrustSettle.Common; -using EntrustSettle.Common.LogHelper; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; -using System; -using System.Threading.Tasks; - -namespace EntrustSettle.Extensions.Middlewares -{ - /// - /// 中间件 - /// 记录IP请求数据 - /// - public class IpLogMiddleware - { - /// - /// - /// - private readonly RequestDelegate _next; - - private readonly IWebHostEnvironment _environment; - - /// - /// - /// - /// - public IpLogMiddleware(RequestDelegate next, IWebHostEnvironment environment) - { - _next = next; - _environment = environment; - } - - public async Task InvokeAsync(HttpContext context) - { - if (AppSettings.app("Middleware", "IPLog", "Enabled").ObjToBool()) - { - // 过滤,只有接口 - if (context.Request.Path.Value.Contains("api")) - { - context.Request.EnableBuffering(); - - - // 存储请求数据 - var request = context.Request; - - var requestInfo = JsonConvert.SerializeObject(new RequestInfo() - { - Ip = GetClientIP(context), - Url = request.Path.ObjToString().TrimEnd('/').ToLower(), - Datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), - Date = DateTime.Now.ToString("yyyy-MM-dd"), - Week = GetWeek(), - }); - - if (!string.IsNullOrEmpty(requestInfo)) - { - // 自定义log输出 - Parallel.For(0, 1, e => - { - //LogLock.OutSql2Log("RequestIpInfoLog", new string[] { requestInfo + "," }, false); - LogLock.OutLogAOP("RequestIpInfoLog", context.TraceIdentifier, - new string[] {requestInfo.GetType().ToString(), requestInfo}, false); - }); - - request.Body.Position = 0; - } - - await _next(context); - } - else - { - await _next(context); - } - } - else - { - await _next(context); - } - } - - private string GetWeek() - { - string week = string.Empty; - switch (DateTime.Now.DayOfWeek) - { - case DayOfWeek.Monday: - week = "周一"; - break; - case DayOfWeek.Tuesday: - week = "周二"; - break; - case DayOfWeek.Wednesday: - week = "周三"; - break; - case DayOfWeek.Thursday: - week = "周四"; - break; - case DayOfWeek.Friday: - week = "周五"; - break; - case DayOfWeek.Saturday: - week = "周六"; - break; - case DayOfWeek.Sunday: - week = "周日"; - break; - default: - week = "N/A"; - break; - } - - return week; - } - - public static string GetClientIP(HttpContext context) - { - var ip = context.Request.Headers["X-Forwarded-For"].ObjToString(); - if (string.IsNullOrEmpty(ip)) - { - ip = context.Connection.RemoteIpAddress.ObjToString(); - } - - return ip; - } - } -} \ No newline at end of file diff --git a/EntrustSettle.Extensions/Middlewares/MiddlewareHelpers.cs b/EntrustSettle.Extensions/Middlewares/MiddlewareHelpers.cs index ab36858..324c8b9 100644 --- a/EntrustSettle.Extensions/Middlewares/MiddlewareHelpers.cs +++ b/EntrustSettle.Extensions/Middlewares/MiddlewareHelpers.cs @@ -44,16 +44,6 @@ namespace EntrustSettle.Extensions.Middlewares return app.UseMiddleware(); } - /// - /// IP请求中间件 - /// - /// - /// - public static IApplicationBuilder UseIpLogMiddle(this IApplicationBuilder app) - { - return app.UseMiddleware(); - } - /// /// 用户访问中间件 /// diff --git a/EntrustSettle.Extensions/Middlewares/RecordAccessLogsMiddleware.cs b/EntrustSettle.Extensions/Middlewares/RecordAccessLogsMiddleware.cs index f699ca6..5cca3e7 100644 --- a/EntrustSettle.Extensions/Middlewares/RecordAccessLogsMiddleware.cs +++ b/EntrustSettle.Extensions/Middlewares/RecordAccessLogsMiddleware.cs @@ -75,7 +75,7 @@ namespace EntrustSettle.Extensions.Middlewares userAccessModel.API = api; userAccessModel.User = _user.Name; - userAccessModel.IP = IpLogMiddleware.GetClientIP(context); + userAccessModel.IP = GetClientIP(context); userAccessModel.BeginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); userAccessModel.RequestMethod = request.Method; userAccessModel.Agent = request.Headers["User-Agent"].ObjToString(); @@ -119,8 +119,17 @@ namespace EntrustSettle.Extensions.Middlewares return Task.CompletedTask; }); } - } + public static string GetClientIP(HttpContext context) + { + var ip = context.Request.Headers["X-Forwarded-For"].ObjToString(); + if (string.IsNullOrEmpty(ip)) + { + ip = context.Connection.RemoteIpAddress.ObjToString(); + } + return ip; + } + } public class UserAccessModel { public string User { get; set; } diff --git a/EntrustSettle.Extensions/Middlewares/RequRespLogMiddleware.cs b/EntrustSettle.Extensions/Middlewares/RequRespLogMiddleware.cs index 42976bf..22f87b3 100644 --- a/EntrustSettle.Extensions/Middlewares/RequRespLogMiddleware.cs +++ b/EntrustSettle.Extensions/Middlewares/RequRespLogMiddleware.cs @@ -77,7 +77,8 @@ namespace EntrustSettle.Extensions.Middlewares var logContent = new string[] { - $"请求 - [Path]:{request.Path}", + $"●请求", + $"[Path]:{request.Path}", $"[QueryString]:{request.QueryString}", $"[Body]:{bodyData}" }; @@ -104,7 +105,8 @@ namespace EntrustSettle.Extensions.Middlewares var logContent = new string[] { - $"响应 - [StatusCode]:{response.StatusCode}", + $"●响应", + $"[StatusCode]:{response.StatusCode}", $"[Body]:{responseBody}", }; Parallel.For(0, 1, e => diff --git a/EntrustSettle.Extensions/ServiceExtensions/AppConfigSetup.cs b/EntrustSettle.Extensions/ServiceExtensions/AppConfigSetup.cs index c28c036..d11b6b7 100644 --- a/EntrustSettle.Extensions/ServiceExtensions/AppConfigSetup.cs +++ b/EntrustSettle.Extensions/ServiceExtensions/AppConfigSetup.cs @@ -87,9 +87,8 @@ namespace EntrustSettle.Extensions List MiddlewareInfos = new() { - new string[] { "请求记录中间件", AppSettings.app("Middleware", "RecordAccessLogs", "Enabled") }, - new string[] { "IP记录中间件", AppSettings.app("Middleware", "IPLog", "Enabled") }, - new string[] { "请求响应日志中间件", AppSettings.app("Middleware", "RequestResponseLog", "Enabled") }, + new string[] { "请求日志记录中间件", AppSettings.app("Middleware", "RecordAccessLogs", "Enabled") }, + new string[] { "请求响应日志记录中间件", AppSettings.app("Middleware", "RequestResponseLog", "Enabled") }, new string[] { "SingnalR实时发送请求数据中间件", AppSettings.app("Middleware", "SignalR", "Enabled") }, new string[] { "IP限流中间件", AppSettings.app("Middleware", "IpRateLimit", "Enabled") }, }; diff --git a/EntrustSettle.Extensions/ServiceExtensions/SqlsugarSetup.cs b/EntrustSettle.Extensions/ServiceExtensions/SqlsugarSetup.cs index 693cb73..3e81711 100644 --- a/EntrustSettle.Extensions/ServiceExtensions/SqlsugarSetup.cs +++ b/EntrustSettle.Extensions/ServiceExtensions/SqlsugarSetup.cs @@ -114,7 +114,11 @@ namespace EntrustSettle.Extensions // 打印SQL语句 dbProvider.Aop.OnLogExecuting = (s, parameters) => { - SqlSugarAop.OnLogExecuting(sql: s, p: parameters, user: App.User?.Name?.ObjToString()); + SqlSugarAop.OnLogExecuting(sql: s, + param: parameters, + path: App.HttpContext?.Request?.Path, + user: App.User?.Name?.ObjToString(), + traceId: App.HttpContext?.TraceIdentifier); }; // 数据初始化