我在一个需要支持基于主机的 Multi-Tenancy 的网站上工作,我已经弄清楚了这整个部分。我遇到的问题是我在 CSS 文件夹中为每个租户 (1,2,3) 都有一个子文件夹。
CSS
|_ tenant_1
|_ tenant_2
|_ tenant_3
|_ tenant (virtual)
tenant_X 文件夹中有自定义的 css 文件,用于为每个特定租户设置样式。
我的想法是以某种方式创建一个虚拟位置(租户),它将映射到租户的文件夹,并且在 _Layout 中只需要额外的一行代码。我对 MVC 并不深入,到目前为止我知道,我想我可以让它与自定义路由一起工作。 这种方法的另一个原因是不允许租户用户看到还有其他租户。我必须排除让用户加载错误文件的可能性。
这是正确的方法吗?你能建议任何更好的方法吗?
最佳答案
仅通过向 _Layout 页面添加 1 行来实现此目的的一种可能实现方式是从 Controller 获取一个 css 文件作为 text/css。
因此假设当前租户 ID 在前端可用,您可以使用该 ID 在 Controller 上调用方法
例如这样的事情:
@Styles.Render(string.Format("/CustomizationController/GetCssForTenant?tenantId={0}", loggedTeanant == null ? (int?) null : loggedTenant.Id))
现在使用如下方法创建一个自定义 Controller
public class CustomizationController : Controller
{
//this will cache cliente side the css file but if the duration expires
// or the tenantId changes it will be ask for the new file
[OutputCache(Duration = 43200, VaryByParam = "tenantId")]
public FileResult GetCssForTenant(int? tenantId)
{
var contentType = "text/css";
//if teanant id is null return empty css file
if(!tenantID.HasValue)
return new FileContentResult(new byte[0], contentType);
//load the real css file here <-
var result = ...
//---
//if having problems with the encoding use this ...
//System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
//var content = encoding.GetBytes(result);
//---
Response.ContentType = contentType;
return new FileContentResult(result, contentType);
//return new FileContentResult(content, contentType);
}
}
希望这有助于实现您的需求。请记住,这是可能实现的草图。
编辑 如果您想快速尝试我建议的实现,请使用此
public class CustomizationController : Controller
{
//this will cache cliente side the css file but if the duration expires
// or the tenantId changes it will be ask for the new file
[OutputCache(Duration = 43200, VaryByParam = "tenantId")]
public FileResult GetCssForTenant(int? tenantId)
{
var contentType = "text/css";
//if teanant id is null return empty css file
if(!tenantID.HasValue)
return new FileContentResult(new byte[0], contentType);
//load the real css file here <-
var result = Environment.NewLine;
if(tenantID = 1)
result "body{ background-color: black !important;}"
else
result "body{ background-color: pink !important;}"
result += Environment.NewLine;
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
var content = encoding.GetBytes(result);
Response.ContentType = contentType;
return new FileContentResult(result, contentType);
}
}
并更改_Layout
@Styles.Render(string.Format("/CustomizationController/GetCssForTenant?tenantId={0}", 1))
现在,如果您发送 1,页面的背景颜色应该变为黑色,如果您发送 2,则变为粉红色。 您还可以在网络中看到,如果您使用相同的 ID 询问 2 次,状态将为 304,这意味着该文件来自缓存。 如果您更改 ID,状态将为 200,即未缓存的响应。
如果您传递 null,css 文件将为空,因此它将回退到您的默认 css。
关于c# - 如何处理 Multi-Tenancy ASP MVC 站点的路径设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36151839/