Browse Source

同步代码

夜鹰 5 tháng trước cách đây
mục cha
commit
94ebcf1786

+ 11 - 3
Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarRepository.cs

@@ -4,6 +4,8 @@
 //
 // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
 
+using NewLife.Reflection;
+
 namespace Admin.NET.Core;
 
 /// <summary>
@@ -36,9 +38,15 @@ public class SqlSugarRepository<T> : SimpleClient<T>, ISqlSugarRepository<T> whe
         if (typeof(T).IsDefined(typeof(SysTableAttribute), false))
             return;
 
-        // 若未贴任何表特性或当前未登录或是默认租户Id,则返回默认库连接
-        var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
-        if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return;
+        // 看请求头有没有租户id
+        var tenantId = App.HttpContext?.Request.Headers.GetValue(ClaimConst.TenantId, false)?.ToString();
+        if (tenantId == SqlSugarConst.MainConfigId) return;
+        else if (string.IsNullOrWhiteSpace(tenantId))
+        {
+            // 若未贴任何表特性或当前未登录或是默认租户Id,则返回默认库连接
+            tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
+            if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return;
+        }
 
         // 根据租户Id切换库连接 为空则返回默认库连接
         var sqlSugarScopeProviderTenant = App.GetRequiredService<SysTenantService>().GetTenantDbConnectionScope(long.Parse(tenantId));

+ 33 - 0
Admin.NET/Admin.NET.Core/Utils/TenantHeaderOperationFilter.cs

@@ -0,0 +1,33 @@
+using Admin.NET.Core;
+using Microsoft.OpenApi.Models;
+using Swashbuckle.AspNetCore.SwaggerGen;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Admin.NET.Core;
+
+/// <summary>
+/// 租户头部参数过滤器
+/// </summary>
+public class TenantHeaderOperationFilter : IOperationFilter
+{
+    /// <summary>
+    /// 应用租户头部参数过滤器
+    /// </summary>
+    public void Apply(OpenApiOperation operation, OperationFilterContext context)
+    {
+        operation.Parameters ??= new List<OpenApiParameter>();
+
+        operation.Parameters.Add(new OpenApiParameter
+        {
+            Name = ClaimConst.TenantId,
+            In = ParameterLocation.Header,
+            Required = false,
+            AllowEmptyValue = true,
+            Description = "租户ID(留空表示默认租户)"
+        });
+    }
+}

+ 1 - 0
Admin.NET/Admin.NET.Web.Core/Startup.cs

@@ -237,6 +237,7 @@ public class Startup : AppStartup
                 Title = "Admin.NET API",
                 Description = "Admin.NET 通用权限开发平台"
             });
+            c.OperationFilter<TenantHeaderOperationFilter>();
         });
 
         // 将IP地址数据库文件完全加载到内存,提升查询速度(以空间换时间,内存将会增加60-70M)