chore: 提交当前变更
This commit is contained in:
@@ -1,39 +1,24 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Module.Tenancy;
|
||||
|
||||
/// <summary>
|
||||
/// 默认租户提供者:优先从Header: X-Tenant-Id,其次从Token Claim: tenant_id
|
||||
/// 默认租户提供者:基于租户上下文访问器暴露当前租户 ID。
|
||||
/// </summary>
|
||||
public sealed class TenantProvider : ITenantProvider
|
||||
{
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly ITenantContextAccessor _tenantContextAccessor;
|
||||
|
||||
public TenantProvider(IHttpContextAccessor httpContextAccessor)
|
||||
/// <summary>
|
||||
/// 初始化租户提供者。
|
||||
/// </summary>
|
||||
/// <param name="tenantContextAccessor">租户上下文访问器</param>
|
||||
public TenantProvider(ITenantContextAccessor tenantContextAccessor)
|
||||
{
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_tenantContextAccessor = tenantContextAccessor;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Guid GetCurrentTenantId()
|
||||
{
|
||||
var httpContext = _httpContextAccessor.HttpContext;
|
||||
if (httpContext == null) return Guid.Empty;
|
||||
|
||||
// 1. Header 优先
|
||||
if (httpContext.Request.Headers.TryGetValue("X-Tenant-Id", out var values))
|
||||
{
|
||||
if (Guid.TryParse(values.FirstOrDefault(), out var headerTenant))
|
||||
return headerTenant;
|
||||
}
|
||||
|
||||
// 2. Token Claim
|
||||
var claim = httpContext.User?.FindFirst("tenant_id");
|
||||
if (claim != null && Guid.TryParse(claim.Value, out var claimTenant))
|
||||
return claimTenant;
|
||||
|
||||
return Guid.Empty; // 未识别到则返回空(上层可按需处理)
|
||||
}
|
||||
=> _tenantContextAccessor.Current?.TenantId ?? Guid.Empty;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user