让我总结一下StoreManage项目的租户策略:
StoreManage 租户解析策略分析
当前状态:写死的调试租户
- TenantMiddleware 中间件
- 位置:Middlewares/TenantMiddleware.cs
- 策略:从配置文件读取固定租户ID
- 配置:
AppSettings:DebugTenantId = "5FF26670-D017-59EE-EE32-3A0DA8CB9375" - 目的:仅供开发调试使用,省去每次手动切换租户的麻烦
public async Task InvokeAsync(HttpContext context, ICurrentTenant currentTenant)
{
// 获取默认租户 ID
var tenantId = _configuration["AppSettings:DebugTenantId"];
if (string.IsNullOrEmpty(tenantId))
await _next(context);
// 如果请求中包含租户 ID,则使用请求中的租户 ID
if (Guid.TryParse(tenantId, out Guid parsedTenantId))
{
if (currentTenant.Id == parsedTenantId)
await _next(context);
else
{
using (currentTenant.Change(parsedTenantId))
{
await _next(context);
}
}
}
ABP 默认支持的租户解析方式
从代码中看到他们使用了 ABP 的默认解析器:
- Cookie:
CookieTenantResolveContributor - QueryString:
QueryStringTenantResolveContributor
但 没有配置 基于域名的解析器!
应该使用的租户解析策略
推荐方案:根据子域名解析
ABP 框架支持多种租户解析方式,常见的有:
| 解析方式 | 示例 | 适用场景 |
|---|---|---|
| 子域名 | tenant1.loda.net.cn |
SaaS应用(推荐) |
| 顶级域名 | tenant1.com |
需要独立域名的高端客户 |
| QueryString | ?__tenant=tenant1 |
开发测试 |
| Header | X-Tenant: tenant1 |
API调用 |
| Cookie | 自动保存 | Web应用 |
如何配置域名租户解析
在 Module 的 ConfigureServices 中添加:
Configure<AbpTenantResolveOptions>(options =>
{
// 1. 子域名解析(推荐)
options.TenantResolvers.Insert(0, new DomainTenantResolveContributor());
// 2. Header解析(用于API)
options.TenantResolvers.Add(new HeaderTenantResolveContributor());
// 3. Cookie解析(用于Web)
options.TenantResolvers.Add(new CookieTenantResolveContributor());
});
域名映射配置
需要在数据库的 AbpTenants 表或 SaasTenants 表中配置:
- TenantName:
ganaju(租户名称) - DomainNames:
ganaju.loda.net.cn(域名列表)
总结
目前状态:
写死租户ID 5FF26670-D017-59EE-EE32-3A0DA8CB9375(柑橘)
仅用于开发调试
生产环境不适用
应该实现:
基于子域名的租户解析
- 柑橘:
ganaju.loda.net.cn - 租户2:
tenant2.loda.net.cn
- 柑橘:
配置 DomainTenantResolveContributor
在数据库中维护租户与域名的映射关系
需要我帮你实现域名租户解析功能吗?
当前发现的关键信息
如何继续?