zhangxiaofeng 8 months ago
commit 07934ee355

@ -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
{

@ -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<bool>("AppSettings:UseLoadTest"))
//{
// app.UseMiddleware<ByPassAuthMiddleware>();
//}
app.UseAuthentication(); // 认证中间件
app.UseAuthorization(); // 授权中间件

@ -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
},
// DBType0=MySql,1=SqlServer,2=Sqlite,3=Oracle,4=PostgreSQL,5=Dm,6=Kdbndp
//

@ -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
},
// DBType0=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
},

@ -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;

@ -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);
}
}
}

@ -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也可以校验可以通过服务或者接口形式

@ -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
{
/// <summary>
/// 中间件
/// 记录IP请求数据
/// </summary>
public class IpLogMiddleware
{
/// <summary>
///
/// </summary>
private readonly RequestDelegate _next;
private readonly IWebHostEnvironment _environment;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
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;
}
}
}

@ -44,16 +44,6 @@ namespace EntrustSettle.Extensions.Middlewares
return app.UseMiddleware<ExceptionHandlerMiddleware>();
}
/// <summary>
/// IP请求中间件
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseIpLogMiddle(this IApplicationBuilder app)
{
return app.UseMiddleware<IpLogMiddleware>();
}
/// <summary>
/// 用户访问中间件
/// </summary>

@ -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; }

@ -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 =>

@ -87,9 +87,8 @@ namespace EntrustSettle.Extensions
List<string[]> 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") },
};

@ -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);
};
// 数据初始化

Loading…
Cancel
Save