优化处理aop获取上下文的信息空异常相关事宜

master
黄欣 10 months ago
parent d8fc9519a0
commit a6e9483a45

@ -4,6 +4,9 @@ using System.Reflection;
namespace DS.Module.AutofacModule; namespace DS.Module.AutofacModule;
/// <summary>
///
/// </summary>
public class AutofacModuleRegister : Autofac.Module public class AutofacModuleRegister : Autofac.Module
{ {
/// <summary> /// <summary>

@ -12,6 +12,15 @@ namespace DS.Module.Core
static AppSetting() static AppSetting()
{ {
//foreach (var xml in Directory.GetFiles(AppContext.BaseDirectory, "*.json"))
//{
// Configuration = new ConfigurationBuilder()
// // .SetBasePath(contentPath)
// .Add(new JsonConfigurationSource { Path = xml, Optional = false, ReloadOnChange = true })
// // .Add(new JsonConfigurationSource { Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", Optional = false, ReloadOnChange = true })
// .Build();
// Console.WriteLine(xml);
//}
string Path = "appsettings.json"; string Path = "appsettings.json";
//ReloadOnChange = true 当appsettings.json被修改时重新加载 //ReloadOnChange = true 当appsettings.json被修改时重新加载
Configuration = new ConfigurationBuilder() Configuration = new ConfigurationBuilder()
@ -44,7 +53,7 @@ namespace DS.Module.Core
return Configuration[string.Join(":", sections)]; return Configuration[string.Join(":", sections)];
} }
} }
catch (Exception) { } catch (Exception ex) { }
return ""; return "";
} }

@ -32,6 +32,7 @@
<PackageReference Include="SKIT.FlurlHttpClient.Wechat.Work" Version="2.25.0" /> <PackageReference Include="SKIT.FlurlHttpClient.Wechat.Work" Version="2.25.0" />
<PackageReference Include="Snowflake.Core" Version="2.0.0" /> <PackageReference Include="Snowflake.Core" Version="2.0.0" />
<PackageReference Include="Snowflake.Data" Version="2.2.0" /> <PackageReference Include="Snowflake.Data" Version="2.2.0" />
<PackageReference Include="SqlSugar.IOC" Version="2.0.0" />
<PackageReference Include="SqlSugarCore" Version="5.1.4.136" /> <PackageReference Include="SqlSugarCore" Version="5.1.4.136" />
</ItemGroup> </ItemGroup>

@ -2,6 +2,9 @@ using DS.Module.Core;
namespace DS.Module.SMS; namespace DS.Module.SMS;
/// <summary>
///
/// </summary>
public interface ISendMessageService public interface ISendMessageService
{ {
Task<DataResult> SendAliYunMessage(TemplateMessages model); Task<DataResult> SendAliYunMessage(TemplateMessages model);

@ -10,6 +10,9 @@ using SqlSugar;
namespace DS.Module.SMS; namespace DS.Module.SMS;
/// <summary>
///
/// </summary>
public class SendMessageService : ISendMessageService public class SendMessageService : ISendMessageService
{ {
private readonly IServiceProvider _serviceProvider; private readonly IServiceProvider _serviceProvider;

@ -11,6 +11,7 @@
<ProjectReference Include="..\DS.Module.Core\DS.Module.Core.csproj" /> <ProjectReference Include="..\DS.Module.Core\DS.Module.Core.csproj" />
<ProjectReference Include="..\DS.Module.Nuget\DS.Module.Nuget.csproj" /> <ProjectReference Include="..\DS.Module.Nuget\DS.Module.Nuget.csproj" />
<ProjectReference Include="..\DS.Module.UserModule\DS.Module.UserModule.csproj" /> <ProjectReference Include="..\DS.Module.UserModule\DS.Module.UserModule.csproj" />
<ProjectReference Include="..\Ds.Modules.DsEntity\Ds.Modules.DsEntity.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

@ -29,6 +29,21 @@ namespace DS.Module.SqlSugar
public DsDataAppService(ISqlSugarClient db) public DsDataAppService(ISqlSugarClient db)
{ {
_db = db; _db = db;
//多租户
_db.Aop.OnExecutingChangeSql = (sql, pars) =>
{
// 在这里,你可以从数据库中加载租户信息,然后修改 SQL 语句。
// 例如,你可以添加一个 WHERE 子句来过滤租户数据。
// 假设你的租户信息存储在一个名为 Tenant 的表中
// var tenantId = ...; // 从某处获取当前租户 ID
// var tenant = _db.Queryable<Tenant>().InSingle(tenantId);
// 然后,你可以修改 SQL 语句,添加一个 WHERE 子句来过滤租户数据
// sql += $" WHERE TenantId = {tenant.Id}";
return new KeyValuePair<string, SugarParameter[]>(sql, pars);
};
} }
/// <summary> /// <summary>
@ -66,7 +81,10 @@ namespace DS.Module.SqlSugar
/// <returns></returns> /// <returns></returns>
public bool Insert(List<T> entities) public bool Insert(List<T> entities)
{ {
return _db.Insertable(entities.ToArray()).ExecuteCommand() > 0; return _db.Insertable(entities.ToArray())
.IgnoreColumns(ignoreNullColumn: true)
.EnableDiffLogEvent()
.ExecuteCommand() > 0;
} }
/// <summary> /// <summary>
@ -76,7 +94,10 @@ namespace DS.Module.SqlSugar
/// <returns></returns> /// <returns></returns>
public bool InsertForEntity(T entity) public bool InsertForEntity(T entity)
{ {
return _db.Insertable(entity).ExecuteCommandIdentityIntoEntity(); return _db.Insertable(entity)
.IgnoreColumns(ignoreNullColumn: true)
.EnableDiffLogEvent()
.ExecuteCommandIdentityIntoEntity();
} }
/// <summary> /// <summary>
@ -86,7 +107,10 @@ namespace DS.Module.SqlSugar
/// <returns></returns> /// <returns></returns>
public bool Update(T entity) public bool Update(T entity)
{ {
return _db.Updateable(entity).ExecuteCommandHasChange(); return _db.Updateable(entity)
.IgnoreColumns(ignoreAllNullColumns: true)
.EnableDiffLogEvent()
.ExecuteCommandHasChange();
} }
/// <summary> /// <summary>
@ -94,12 +118,15 @@ namespace DS.Module.SqlSugar
/// </summary> /// </summary>
/// <param name="entity"></param> /// <param name="entity"></param>
/// <returns></returns> /// <returns></returns>
public bool InsertForTran(T entity) public async Task<bool> InsertForTran(T entity)
{ {
try try
{ {
_db.Ado.BeginTran(); _db.Ado.BeginTran();
var result = _db.Insertable(entity).ExecuteCommandIdentityIntoEntity(); var result = await _db.Insertable(entity)
.IgnoreColumns(ignoreNullColumn: true)
.EnableDiffLogEvent()
.ExecuteCommandIdentityIntoEntityAsync();
_db.Ado.CommitTran(); _db.Ado.CommitTran();
return result; return result;
} }
@ -122,7 +149,10 @@ namespace DS.Module.SqlSugar
try try
{ {
_db.Ado.BeginTran(); _db.Ado.BeginTran();
var result = _db.Updateable(entity).ExecuteCommandHasChange(); var result = _db.Updateable(entity)
.IgnoreColumns(ignoreAllNullColumns: true)
.EnableDiffLogEvent()
.ExecuteCommandHasChange();
_db.Ado.CommitTran(); _db.Ado.CommitTran();
return result; return result;
} }
@ -145,7 +175,9 @@ namespace DS.Module.SqlSugar
try try
{ {
_db.Ado.BeginTran(); _db.Ado.BeginTran();
var result = _db.Deleteable(entity).ExecuteCommandHasChange(); var result = _db.Deleteable(entity)
.EnableDiffLogEvent()
.ExecuteCommandHasChange();
_db.Ado.CommitTran(); _db.Ado.CommitTran();
return result; return result;
} }
@ -163,7 +195,9 @@ namespace DS.Module.SqlSugar
/// <returns></returns> /// <returns></returns>
public bool Delete(T entity) public bool Delete(T entity)
{ {
return _db.Deleteable(entity).ExecuteCommandHasChange(); return _db.Deleteable(entity)
.EnableDiffLogEvent()
.ExecuteCommandHasChange();
} }
/// <summary> /// <summary>

@ -1,6 +1,7 @@
using Ds.Module.AppStartup; using Ds.Module.AppStartup;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using SqlSugar.IOC;
namespace DS.Module.SqlSugar namespace DS.Module.SqlSugar
{ {
@ -13,7 +14,40 @@ namespace DS.Module.SqlSugar
public void ConfigureServices(WebApplicationBuilder builder) public void ConfigureServices(WebApplicationBuilder builder)
{ {
SugarIocServices.AddSqlSugar(new IocConfig()
{
ConfigId = 200,// 多租户用到
ConnectionString = "server=60.209.125.238;port=32006;uid=root;pwd=Djy@Mysql.test;database=shippingweb8_log",
DbType = IocDbType.MySql,
IsAutoCloseConnection = true//自动释放
}); //多
SugarIocServices.ConfigurationSugar(db =>
{
db.Aop.OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
};
//设置更多连接参数
//db.CurrentConnectionConfig.XXXX=XXXX
//db.CurrentConnectionConfig.MoreSettings=new ConnMoreSettings(){}
//二级缓存设置
//db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
//{
// DataInfoCacheService = myCache //配置我们创建的缓存类
//}
//读写分离设置
//laveConnectionConfigs = new List<SlaveConnectionConfig>(){...}
/*多租户注意*/
//单库是db.CurrentConnectionConfig
//多租户需要db.GetConnection(configId).CurrentConnectionConfig
//db.GetConnection(200).CodeFirst.SetStringDefaultLength(500).InitTables(typeof(Sys_Log_DataAop));
});
//数据操作仓储
builder.Services.AddScoped(typeof(DsDataAppService<>)); builder.Services.AddScoped(typeof(DsDataAppService<>));
//sqlsugar注册
builder.Services.AddSqlsugarInstall(); builder.Services.AddSqlsugarInstall();
} }
} }

@ -1,6 +1,9 @@
using DS.Module.Core.Data; using Ds.Modules.DsEntity.log;
using DS.Module.Core.Data;
using DS.Module.UserModule; using DS.Module.UserModule;
using Newtonsoft.Json;
using SqlSugar; using SqlSugar;
using SqlSugar.IOC;
namespace DS.Module.SqlSugar namespace DS.Module.SqlSugar
{ {
@ -23,7 +26,7 @@ namespace DS.Module.SqlSugar
/* /*
* / * /
*/ */
Console.WriteLine("开始加载sqlsugar模块"); Console.WriteLine("开始加载sqlsugar模块 要走过滤 起了");
foreach (var c in connectConfigList) foreach (var c in connectConfigList)
{ {
var dbProvider = db.GetConnectionScope((string)c.ConfigId); var dbProvider = db.GetConnectionScope((string)c.ConfigId);
@ -36,6 +39,7 @@ namespace DS.Module.SqlSugar
//Logger.Log(LogLevel.Info, //Logger.Log(LogLevel.Info,
// DateTime.Now.ToString() + "\r\n" + // DateTime.Now.ToString() + "\r\n" +
// UtilMethods.GetSqlString(c.DbType, sql, pars)); // UtilMethods.GetSqlString(c.DbType, sql, pars));
Console.WriteLine("执行的sql:" + sql);
}; };
//数据处理事件 //数据处理事件
@ -46,25 +50,33 @@ namespace DS.Module.SqlSugar
// 更新操作 // 更新操作
SqlsugarHelper.UpdateByObjectForSqlsugar(entityInfo, user); SqlsugarHelper.UpdateByObjectForSqlsugar(entityInfo, user);
}; };
dbProvider.Aop.OnError = (exp) => //执行SQL 错误事件
{
// Logger.Error(DateTime.Now.ToString() + "\r\n" + exp.Sql + "\r\n" + exp.Parametres);
};
db.Aop.OnDiffLogEvent = it => dbProvider.Aop.OnDiffLogEvent = (it) =>
{ {
Console.WriteLine("执行更新前更新后:");
//操作前记录 包含: 字段描述 列名 值 表名 表描述 //操作前记录 包含: 字段描述 列名 值 表名 表描述
var editBeforeData = it.BeforeData;//插入Before为null之前还没进库 //var editBeforeData = it.BeforeData;//插入Before为null之前还没进库
//操作后记录 包含: 字段描述 列名 值 表名 表描述 // //操作后记录 包含: 字段描述 列名 值 表名 表描述
var editAfterData = it.AfterData; //var editAfterData = it.AfterData;
var sql = it.Sql; //var sql = it.Sql;
var parameter = it.Parameters; //var parameter = it.Parameters;
var data = it.BusinessData;//这边会显示你传进来的对象 //var data = it.BusinessData;//这边会显示你传进来的对象
var time = it.Time; //var time = it.Time;
var diffType = it.DiffType;//enum insert 、update and delete //var diffType = it.DiffType;//enum insert 、update and delete
// Sys_Log_DataAop
Console.WriteLine("执行的sql:" + sql); var log = new Sys_Log_DataAop()
{
EditBeforeData = it.BeforeData?.ToString() ?? "123",
EditAfterData = it.AfterData?.ToString(),
Aop_Sql = it.Sql,
Parameter = JsonConvert.SerializeObject(it.Parameters),
Aop_Data = it.BusinessData?.ToString() ?? "12131",
Aop_Time = it.Time.ToString(),
DiffType = it.DiffType.ToString()
};
Console.WriteLine("执行的sql:" + log);
//Write logic //Write logic
DbScoped.Sugar.GetConnection(200).Insertable(log).ExecuteCommand();
}; };
dbProvider.QueryFilter.AddTableFilter<ITenantId>(m => m.TenantId == user.GetTenantId()); dbProvider.QueryFilter.AddTableFilter<ITenantId>(m => m.TenantId == user.GetTenantId());
//全局软删除过滤 //全局软删除过滤

@ -1,13 +1,14 @@
using DS.Module.Core; using DS.Module.Core;
using DS.Module.Core.Data;
using DS.Module.Core.Extensions;
using DS.Module.UserModule; using DS.Module.UserModule;
using Microsoft.IdentityModel.Tokens;
using SqlSugar; using SqlSugar;
namespace DS.Module.SqlSugar namespace DS.Module.SqlSugar
{ {
public static class SqlsugarHelper public static class SqlsugarHelper
{ {
#region 新增操作 + InsertByObjectForSqlsugar
/// <summary> /// <summary>
/// 新增操作 /// 新增操作
/// </summary> /// </summary>
@ -35,7 +36,7 @@ namespace DS.Module.SqlSugar
entityInfo.SetValue(DateTime.Now); entityInfo.SetValue(DateTime.Now);
if (!user.UserId.IsNullOrEmpty()) if (!user.UserId.IsNullOrEmpty())
{ {
if (entityInfo.PropertyName == "TenantId") if (entityInfo.PropertyName == "TenantId" || entityInfo.PropertyName == "TenantNumber")
entityInfo.SetValue(user.GetTenantId()); entityInfo.SetValue(user.GetTenantId());
} }
@ -56,6 +57,10 @@ namespace DS.Module.SqlSugar
} }
} }
#endregion 新增操作 + InsertByObjectForSqlsugar
#region 更新操作 +++ UpdateByObjectForSqlsugar
/// <summary> /// <summary>
/// 更新操作 /// 更新操作
/// </summary> /// </summary>
@ -73,6 +78,15 @@ namespace DS.Module.SqlSugar
} }
} }
#endregion 更新操作 +++ UpdateByObjectForSqlsugar
#region 加载配置文件 + ReturnConnectionConfig
/// <summary>
/// 加载配置文件
/// </summary>
/// <param name="dbList"></param>
/// <returns></returns>
public static List<ConnectionConfig> ReturnConnectionConfig(List<DbConfig> dbList) public static List<ConnectionConfig> ReturnConnectionConfig(List<DbConfig> dbList)
{ {
var connectConfigList = new List<ConnectionConfig>(); var connectConfigList = new List<ConnectionConfig>();
@ -104,5 +118,7 @@ namespace DS.Module.SqlSugar
} }
return connectConfigList; return connectConfigList;
} }
#endregion 加载配置文件 + ReturnConnectionConfig
} }
} }

@ -1,8 +1,8 @@
using DS.Module.Core; using DS.Module.Core;
using DS.Module.Core.Extensions; using DS.Module.Core.Extensions;
using DS.Module.UserModule; using DS.Module.UserModule;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NLog;
using SqlSugar; using SqlSugar;
namespace DS.Module.SqlSugar; namespace DS.Module.SqlSugar;
@ -22,7 +22,7 @@ public static class SqlsugarInstall
// /// </summary> // /// </summary>
// private static string DbType = AppSetting.Configuration["ConnectionStrings:DbType"]; // private static string DbType = AppSetting.Configuration["ConnectionStrings:DbType"];
public static readonly Logger Logger = LogManager.GetCurrentClassLogger(); //public static readonly Logger Logger = LogManager.GetCurrentClassLogger();
// private readonly IUser user; // private readonly IUser user;
// private ILogger<SqlsugarInstall> _logger; // private ILogger<SqlsugarInstall> _logger;
@ -81,6 +81,17 @@ public static class SqlsugarInstall
// }); // });
//} //}
var user = services.GetService<IUser>(); var user = services.GetService<IUser>();
if (user.IsNullOrEmpty())
{
var httpContextAccessor = services.GetService<IHttpContextAccessor>();
user = new AspNetUser(httpContextAccessor)
{
UserId = "1288018625843826688",
TenantId = "1288018625843826688",
CompanyId = "1288018625843826688",
OrgId = "1288018625843826688"
};
}
//全局上下文生效 //全局上下文生效
SqlSugarScope sqlSugar = new SqlSugarScope(connectConfigList, SqlSugarScope sqlSugar = new SqlSugarScope(connectConfigList,
db => db =>

@ -0,0 +1,64 @@
using SqlSugar;
#region << 版 本 注 释 >>
/*
* c2024
* CLR 4.0.30319.42000
*
*
*
*
*
*
*/
#endregion << 版 本 注 释 >>
namespace DS.Module.SqlSugar.aop
{
public class SqlSugarAop
{
private readonly ISqlSugarClient _tenantDb;
public SqlSugarAop(ISqlSugarClient tenantDb)
{
_tenantDb = tenantDb;
}
public KeyValuePair<string, SugarParameter[]> OnExecutingChangeSql(string sql, SugarParameter[] pars)
{
// 在这里,你可以从另一个数据库中加载租户信息,然后修改 SQL 语句。
// 例如,你可以添加一个 WHERE 子句来过滤租户数据。
// 假设你的租户信息存储在一个名为 Tenant 的表中
//var tenantId = ...; // 从某处获取当前租户 ID
//var tenant = _tenantDb.Queryable<Tenant>().InSingle(tenantId);
//// 然后,你可以修改 SQL 语句,添加一个 WHERE 子句来过滤租户数据
//sql += $" WHERE TenantId = {tenant.Id}";
return new KeyValuePair<string, SugarParameter[]>(sql, pars);
}
public void OnLogExecuting(string sql, SugarParameter[] pars)
{
// 在这里,你可以记录 SQL 语句和参数。
}
public void OnLogExecuted(string sql, SugarParameter[] pars)
{
// 在这里,你可以记录 SQL 语句和参数。
}
public void OnError(Exception ex)
{
// 在这里,你可以处理数据库操作的异常。
}
public void OnDiffLogEvent(DiffLogModel diffLogModel)
{
// 在这里,你可以处理差异日志事件。
}
}
}

@ -18,127 +18,386 @@ public class AspNetUser : IUser
public UserInfo UserInfo => GetUserInfo(); public UserInfo UserInfo => GetUserInfo();
public string GetToken() //public string GetToken()
//{
// return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
//}
//public string UserId => GetClaimValueByType("jti").FirstOrDefault().ObjToString();
private string _userId;
public string UserId
{ {
return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", ""); get
{
if (_userId == null)
{
var claimValue = GetClaimValueByType("jti").FirstOrDefault();
_userId = claimValue != null ? claimValue.ObjToString() : "东胜软件";
}
return _userId;
}
set
{
_userId = value;
}
} }
public string UserId => GetClaimValueByType("jti").FirstOrDefault().ObjToString();
public long GetTenantId() public long GetTenantId()
{ {
// return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", ""); var token = GetToken();
var tenantId = String.Empty; if (string.IsNullOrEmpty(token))
var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last() {
?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault() return 0;
?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault() }
?? _accessor.HttpContext?.Request.Cookies["Token"];
// token校验
var jwtHandler = new JwtSecurityTokenHandler(); var jwtHandler = new JwtSecurityTokenHandler();
if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token)) if (!jwtHandler.CanReadToken(token))
{ {
return 0;
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token); JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var tenantIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "TenantId");
tenantId = jwtToken.Claims.First(x => x.Type == "TenantId").Value; return tenantIdClaim != null ? Convert.ToInt64(tenantIdClaim.Value) : 0;
} }
return Convert.ToInt64(tenantId); //public long GetTenantId()
} //{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var tenantId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// tenantId = jwtToken.Claims.First(x => x.Type == "TenantId").Value;
// }
// return Convert.ToInt64(tenantId);
//}
public long GetOrgId() public long GetOrgId()
{ {
// return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", ""); var token = GetToken();
var orgId = String.Empty; if (string.IsNullOrEmpty(token))
var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last() {
?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault() return 0;
?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault() }
?? _accessor.HttpContext?.Request.Cookies["Token"];
// token校验
var jwtHandler = new JwtSecurityTokenHandler(); var jwtHandler = new JwtSecurityTokenHandler();
if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token)) if (!jwtHandler.CanReadToken(token))
{ {
return 0;
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token); JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var orgIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "OrgId");
orgId = jwtToken.Claims.First(x => x.Type == "OrgId").Value; return orgIdClaim != null ? Convert.ToInt64(orgIdClaim.Value) : 0;
}
return Convert.ToInt64(orgId);
} }
//public long GetOrgId()
//{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var orgId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// orgId = jwtToken.Claims.First(x => x.Type == "OrgId").Value;
// }
// return Convert.ToInt64(orgId);
//}
//public string GetCompanyId()
//{
// // return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", "");
// var companyId = String.Empty;
// var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault()
// ?? _accessor.HttpContext?.Request.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// companyId = jwtToken.Claims.First(x => x.Type == "OrgId").Value;
// }
// return companyId;
//}
public string GetCompanyId() public string GetCompanyId()
{ {
// return _accessor.HttpContext?.Request?.Headers["Authorization"].ToString().Replace("Bearer ", ""); var token = GetToken();
var companyId = String.Empty; if (string.IsNullOrEmpty(token))
var token = _accessor.HttpContext?.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last() {
?? _accessor.HttpContext?.Request.Headers["X-Token"].FirstOrDefault() return string.Empty;
?? _accessor.HttpContext?.Request.Query["Token"].FirstOrDefault() }
?? _accessor.HttpContext?.Request.Cookies["Token"];
// token校验
var jwtHandler = new JwtSecurityTokenHandler(); var jwtHandler = new JwtSecurityTokenHandler();
if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token)) if (!jwtHandler.CanReadToken(token))
{ {
return string.Empty;
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token); JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var companyIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "OrgId");
return companyIdClaim?.Value ?? "0000000001";
}
//public string TenantId => GetClaimValueByType("TenantId").FirstOrDefault().ObjToString();
private string _tenantId;
companyId = jwtToken.Claims.First(x => x.Type == "OrgId").Value; public string TenantId
{
get
{
if (_tenantId == null)
{
var tenantIdClaim = GetClaimValueByType("TenantId").FirstOrDefault();
_tenantId = tenantIdClaim != null ? tenantIdClaim.ObjToString() : "00000000000001";
}
return _tenantId;
}
set
{
_tenantId = value;
} }
return companyId;
} }
// public string CompanyId => GetClaimValueByType("CompanyId").FirstOrDefault().ObjToString();
private string _companyId;
public string TenantId => GetClaimValueByType("TenantId").FirstOrDefault().ObjToString(); public string CompanyId
{
get
{
if (_companyId == null)
{
var companyIdClaim = GetClaimValueByType("CompanyId").FirstOrDefault();
_companyId = companyIdClaim != null ? companyIdClaim.ObjToString() : "东胜软件";
}
return _companyId;
}
set
{
_companyId = value;
}
}
public string CompanyId => GetClaimValueByType("CompanyId").FirstOrDefault().ObjToString(); // public string OrgId => GetClaimValueByType("OrgId").FirstOrDefault().ObjToString();
private string _orgId;
public string OrgId => GetClaimValueByType("OrgId").FirstOrDefault().ObjToString(); public string OrgId
{
get
{
if (_orgId == null)
{
var orgIdClaim = GetClaimValueByType("OrgId").FirstOrDefault();
_orgId = orgIdClaim != null ? orgIdClaim.ObjToString() : "1111111111";
}
return _orgId;
}
set
{
_orgId = value;
}
}
public UserInfo GetUserInfo() public UserInfo GetUserInfo()
{ {
if (_accessor.HttpContext.User.Claims == null) var user = _accessor.HttpContext?.User;
if (user == null || !user.Claims.Any())
{ {
return null; return GetDefaultUserInfo();
}
var token = GetToken();
if (string.IsNullOrEmpty(token))
{
return GetDefaultUserInfo();
} }
var json = _accessor.HttpContext.User.Claims;
//获取上传token可自定义扩展
var token = _accessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
?? _accessor.HttpContext.Request.Headers["X-Token"].FirstOrDefault()
?? _accessor.HttpContext.Request.Query["Token"].FirstOrDefault()
?? _accessor.HttpContext.Request.Cookies["Token"];
// token校验
var jwtHandler = new JwtSecurityTokenHandler(); var jwtHandler = new JwtSecurityTokenHandler();
var userInfo = new UserInfo(); if (!jwtHandler.CanReadToken(token))
if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
{ {
return GetDefaultUserInfo();
}
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token); JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
var UserId = jwtToken.Claims.First().Value; var userInfoJson = jwtToken.Claims.First().Value;
// userInfo = db.Queryable<SysUser>() var userInfo = JsonConvert.DeserializeObject<UserInfo>(userInfoJson);
// .Where(a =>
// a.Deleted == false && a.Id == user.Id) return userInfo ?? GetDefaultUserInfo();
// .Select(a => new UserInfo }
// {
// UserId = a.Id, UserCode = a.UserCode, UserName = a.NickName, private UserInfo GetDefaultUserInfo()
// // OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName {
// }).First(); return new UserInfo()
// var t1 = JsonConvert.DeserializeObject<UserInfo>(temp); {
userInfo = JsonConvert.DeserializeObject<UserInfo>(jwtToken.Claims.First().Value); CompanyId = "000001",
CompanyName = "东胜软件",
Token = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiIsImFkbWluIjp0cnVlfQ",
UserCode = "0000001",
UserId = "00000000",
UserName = "东胜软件",
};
}
public string GetToken()
{
if (_accessor == null || _accessor.HttpContext == null)
{
return "东胜软件";
}
var request = _accessor.HttpContext.Request;
var authorizationHeader = request.Headers["Authorization"].FirstOrDefault();
if (!string.IsNullOrEmpty(authorizationHeader))
{
return authorizationHeader.Split(" ").Last();
} }
return userInfo; return request.Headers["X-Token"].FirstOrDefault()
?? request.Query["Token"].FirstOrDefault()
?? request.Cookies["Token"]
?? "东胜软件";
} }
#region 优化前
//public string GetToken()
//{
// var headers = _accessor.HttpContext?.Request?.Headers;
// if (headers != null && headers.ContainsKey("Authorization"))
// {
// return headers["Authorization"].ToString().Replace("Bearer ", "");
// }
// return null;
//}
//public UserInfo GetUserInfo()
//{
// if (_accessor.HttpContext.User.Claims == null)
// {
// return new UserInfo()
// {
// CompanyId = "1",
// CompanyName = "初始化",
// Token = "初始化",
// UserCode = "初始化",
// UserId = "00000000",
// UserName = "初始化",
// };
// }
// //var json = _accessor.HttpContext.User.Claims;
// //获取上传token可自定义扩展
// var httphedad = _accessor.HttpContext.Request;
// var token = httphedad.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last()
// ?? httphedad.Headers["X-Token"].FirstOrDefault()
// ?? httphedad.Query["Token"].FirstOrDefault()
// ?? httphedad.Cookies["Token"];
// // token校验
// var jwtHandler = new JwtSecurityTokenHandler();
// var userInfo = new UserInfo();
// if (!token.IsNullOrEmpty() && jwtHandler.CanReadToken(token))
// {
// JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
// var UserId = jwtToken.Claims.First().Value;
// // userInfo = db.Queryable<SysUser>()
// // .Where(a =>
// // a.Deleted == false && a.Id == user.Id)
// // .Select(a => new UserInfo
// // {
// // UserId = a.Id, UserCode = a.UserCode, UserName = a.NickName,
// // // OrgId = a.OrgId.ToString(), CompanyName = a.CustomerName
// // }).First();
// // var t1 = JsonConvert.DeserializeObject<UserInfo>(temp);
// userInfo = JsonConvert.DeserializeObject<UserInfo>(jwtToken.Claims.First().Value);
// }
// return userInfo;
//}
//public IEnumerable<Claim> GetClaimsIdentity()
//{
// var claims = _accessor.HttpContext.User.Claims.ToList();
// var headers = _accessor.HttpContext.Request.Headers;
// foreach (var header in headers)
// {
// claims.Add(new Claim(header.Key, header.Value));
// }
// return claims;
//}
#endregion 优化前
/// <summary>
/// 保持在请求上下文中的所有声明 不为空
/// </summary>
/// <returns></returns>
public IEnumerable<Claim> GetClaimsIdentity() public IEnumerable<Claim> GetClaimsIdentity()
{ {
var claims = _accessor.HttpContext.User.Claims.ToList(); var claims = new List<Claim>();
var headers = _accessor.HttpContext.Request.Headers; var user = _accessor.HttpContext?.User;
if (user != null)
{
claims.AddRange(user.Claims);
}
var headers = _accessor.HttpContext?.Request?.Headers;
if (headers != null)
{
foreach (var header in headers) foreach (var header in headers)
{ {
claims.Add(new Claim(header.Key, header.Value)); foreach (var value in header.Value)
{
if (!string.IsNullOrEmpty(value))
{
claims.Add(new Claim(header.Key, value));
}
}
} }
}
return claims; return claims;
} }
#region 键值对获取相应的内容 如果内容不存在则返回默认值 GetClaimValueByType
/// <summary>
/// 键值对获取相应的内容 如果内容不存在则返回默认值
/// </summary>
/// <param name="ClaimType"></param>
/// <returns></returns>
public List<string> GetClaimValueByType(string ClaimType) public List<string> GetClaimValueByType(string ClaimType)
{ {
return (from item in GetClaimsIdentity() var claimsIdentity = GetClaimsIdentity();
where item.Type == ClaimType if (claimsIdentity == null || !claimsIdentity.Any(item => item.Type == ClaimType))
select item.Value).ToList(); {
return new List<string> { "jti", "TenantId", "CompanyId", "OrgId" }; // 返回包含默认参数的列表
} }
return claimsIdentity.Where(item => item.Type == ClaimType).Select(item => item.Value).ToList();
}
#endregion 键值对获取相应的内容 如果内容不存在则返回默认值 GetClaimValueByType
} }

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Ds.Module.AppStartup\Ds.Module.AppStartup.csproj" />
<ProjectReference Include="..\DS.Module.Core\DS.Module.Core.csproj" /> <ProjectReference Include="..\DS.Module.Core\DS.Module.Core.csproj" />
</ItemGroup> </ItemGroup>

@ -0,0 +1,37 @@
using Ds.Module.AppStartup;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
#region << 版 本 注 释 >>
/*
* c2024
* CLR 4.0.30319.42000
*
*
*
*
*
*
*/
#endregion << 版 本 注 释 >>
namespace DS.Module.UserModule
{
[DsStartup(4)]
public class UserModuleAppStartup : IDynamicStartup
{
public void Configure(WebApplication app)
{
}
public void ConfigureServices(WebApplicationBuilder builder)
{
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddScoped<IUser, AspNetUser>();
// builder.Services.AddUserModuleInstall();
}
}
}

@ -4,19 +4,18 @@ using Ds.WMS.WebCore.appstartup;
var builder = WebApplication.CreateBuilder(args).UseMyConfiguration(); var builder = WebApplication.CreateBuilder(args).UseMyConfiguration();
// ʹ<EFBFBD>ö<EFBFBD>̬<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EBBCAF> webcore <20><><EFBFBD><EFBFBD>ʵ<EFBFBD><CAB5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC>Ľ<EFBFBD><C4BD><EFBFBD> // 添加中间件
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddControllers(options => builder.Services.AddControllers(options =>
{ {
// options.Filters.Add<DsAppActionFilterFactory>();
options.Filters.Add(new DsAppActionFilterFactory()); options.Filters.Add(new DsAppActionFilterFactory());
}); });
builder.UseDynamicStartups(); builder.UseDynamicStartups();
var app = builder.Build(); var app = builder.Build();
// <EFBFBD>м<EFBFBD><EFBFBD> // 中间件
app.UseMyMiddlewares(); app.UseMyMiddlewares();
app.Run(); app.Run();

@ -1,7 +1,7 @@
namespace Ds.Module.AppStartup namespace Ds.Module.AppStartup
{ {
/// <summary> /// <summary>
/// ///标记启动顺序
/// </summary> /// </summary>
[AttributeUsage(AttributeTargets.Class)] [AttributeUsage(AttributeTargets.Class)]
public class DsStartupAttribute : Attribute public class DsStartupAttribute : Attribute
@ -13,6 +13,4 @@
Order = order; Order = order;
} }
} }
} }

@ -2,10 +2,21 @@
namespace Ds.Module.AppStartup namespace Ds.Module.AppStartup
{ {
/// <summary>
///
/// </summary>
public interface IDynamicStartup public interface IDynamicStartup
{ {
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
public void ConfigureServices(WebApplicationBuilder builder); public void ConfigureServices(WebApplicationBuilder builder);
/// <summary>
///
/// </summary>
/// <param name="app"></param>
public void Configure(WebApplication app); public void Configure(WebApplication app);
} }
} }

@ -89,18 +89,29 @@ namespace Ds.Modules.DsEntity.Base
public long Id { get; set; } public long Id { get; set; }
} }
public abstract class BasEntityTenantForIsIdentity : BaseComEntity
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]//数据库是自增才配自增
public long Id { get; set; }
/// <summary>
/// 租户编号
/// </summary>
public string TenantNumber { get; set; } = "123";
}
/// <summary> /// <summary>
/// 租户雪花ID实体基类 /// 租户雪花ID实体基类
/// </summary> /// </summary>
public abstract class BaseEntityTenant : BaseComEntity public abstract class BaseEntityTenant : BaseComEntity
{ {
[SugarColumn(IsPrimaryKey = true)] [SugarColumn(IsPrimaryKey = true)]
public long Id { get; set; } public long Id { get; set; } = 111111111111111;
/// <summary> /// <summary>
/// 租户编号 /// 租户编号
/// </summary> /// </summary>
public string TenantNumber { get; set; } public string TenantNumber { get; set; } = "123";
} }
/// <summary> /// <summary>

@ -0,0 +1,36 @@
#region << 版 本 注 释 >>
/*
* c2024
* CLR 4.0.30319.42000
*
*
*
*
*
*
*/
#endregion << 版 本 注 释 >>
namespace Ds.Modules.DsEntity.log
{
/// <summary>
///
/// </summary>
public class Sys_Log_DataAop : BasEntityTenantForIsIdentity
{
//操作前记录 包含: 字段描述 列名 值 表名 表描述
public string? EditBeforeData { get; set; } = "123";// = it.BeforeData;//插入Before为null之前还没进库
//操作后记录 包含: 字段描述 列名 值 表名 表描述
public string? EditAfterData { get; set; } = "123";// = it.AfterData;
public string? Aop_Sql { get; set; } = "123";
public string? Parameter { get; set; } = "123";// = it.Parameters;
public string? Aop_Data { get; set; } = "123";//= it.BusinessData;//这边会显示你传进来的对象
public string Aop_Time { get; set; } = "123";//= it.Time;
public string DiffType { get; set; } = "123"; //= it.DiffType;//enum insert 、update and delete
}
}

@ -9,17 +9,15 @@ namespace Ds.WMS.Finance.MediatR.handlers
{ {
private readonly DsDataAppService<Code_Currency> _db; private readonly DsDataAppService<Code_Currency> _db;
/// <summary>
///
/// </summary>
/// <param name="db"></param>
public GetCostBasicHandler(DsDataAppService<Code_Currency> db) public GetCostBasicHandler(DsDataAppService<Code_Currency> db)
{ {
_db = db; _db = db;
} }
//private readonly ISqlSugarClient _db;
//public GetCostBasicHandler(ISqlSugarClient db)
//{
// _db = db;
//}
/// <summary> /// <summary>
/// 具体的业务逻辑 /// 具体的业务逻辑
/// </summary> /// </summary>
@ -28,11 +26,6 @@ namespace Ds.WMS.Finance.MediatR.handlers
/// <returns></returns> /// <returns></returns>
async Task<CurrencyDto> IRequestHandler<CostExchangeRateCommand, CurrencyDto>.Handle(CostExchangeRateCommand request, CancellationToken cancellationToken) async Task<CurrencyDto> IRequestHandler<CostExchangeRateCommand, CurrencyDto>.Handle(CostExchangeRateCommand request, CancellationToken cancellationToken)
{ {
//var list = await _db.Queryable<Code_Currency>()
// .Where(x => x.Id == request.Id)
// .Select<CurrencyDto>()
// .FirstAsync();
// 使用 QueryForOneEntity<TResult> 方法
var list = await _db.QueryForOneEntity<CurrencyDto>(x => x.Id == request.Id); var list = await _db.QueryForOneEntity<CurrencyDto>(x => x.Id == request.Id);
return await Task.FromResult(list); return await Task.FromResult(list);
@ -44,23 +37,27 @@ namespace Ds.WMS.Finance.MediatR.handlers
/// </summary> /// </summary>
public class AddCostBasicHandler : IRequestHandler<CostExchangeForAddCommand, bool> public class AddCostBasicHandler : IRequestHandler<CostExchangeForAddCommand, bool>
{ {
private readonly ISqlSugarClient _db; private readonly DsDataAppService<Code_Currency> _db;
public AddCostBasicHandler(ISqlSugarClient db) /// <summary>
///
/// </summary>
/// <param name="db"></param>
public AddCostBasicHandler(DsDataAppService<Code_Currency> db)
{ {
_db = db; _db = db;
} }
public async Task<bool> Handle(CostExchangeForAddCommand request, CancellationToken cancellationToken) public async Task<bool> Handle(CostExchangeForAddCommand request, CancellationToken cancellationToken)
{ {
var list = await _db.Insertable<Code_Currency>(new Code_Currency() var list = await _db.InsertForTran(new Code_Currency()
{ {
CodeName = request.CodeName, CodeName = request.CodeName,
DefaultRate = request.DefaultRate, DefaultRate = request.DefaultRate,
Description = request.Description, Description = request.Description,
FinanceSoftCodes = request.FinanceSoftCodes, FinanceSoftCodes = request.FinanceSoftCodes,
Name = request.Name Name = request.Name
}).ExecuteCommandAsync() > 0; });
return await Task.FromResult(list); return await Task.FromResult(list);
} }
} }

@ -12,6 +12,7 @@
<ProjectReference Include="..\DS.Module.Nuget\DS.Module.Nuget.csproj" /> <ProjectReference Include="..\DS.Module.Nuget\DS.Module.Nuget.csproj" />
<ProjectReference Include="..\DS.Module.SqlSugar\DS.Module.SqlSugar.csproj" /> <ProjectReference Include="..\DS.Module.SqlSugar\DS.Module.SqlSugar.csproj" />
<ProjectReference Include="..\DS.Module.Swagger\DS.Module.Swagger.csproj" /> <ProjectReference Include="..\DS.Module.Swagger\DS.Module.Swagger.csproj" />
<ProjectReference Include="..\DS.Module.UserModule\DS.Module.UserModule.csproj" />
<ProjectReference Include="..\Ds.Modules.DsEntity\Ds.Modules.DsEntity.csproj" /> <ProjectReference Include="..\Ds.Modules.DsEntity\Ds.Modules.DsEntity.csproj" />
<ProjectReference Include="..\Ds.WMS.Finance.MediatR\Ds.WMS.Finance.MediatR.csproj" /> <ProjectReference Include="..\Ds.WMS.Finance.MediatR\Ds.WMS.Finance.MediatR.csproj" />
<ProjectReference Include="..\Ds.WMS.MogonDb\Ds.WMS.MogonDb.csproj" /> <ProjectReference Include="..\Ds.WMS.MogonDb\Ds.WMS.MogonDb.csproj" />

@ -35,7 +35,8 @@ namespace Ds.WMS.WebCore.appstartup
"Ds.WMS.Finance.MediatR", "Ds.WMS.Finance.MediatR",
"DS.Module.SqlSugar", "DS.Module.SqlSugar",
"Ds.WMS.MogonDb", "Ds.WMS.MogonDb",
"DS.Module.Swagger" "DS.Module.Swagger",
"DS.Module.UserModule"
// 其他程序集的名称... // 其他程序集的名称...
}; };

Loading…
Cancel
Save