我正在使用ASP.NET MVC构建一个多租户应用程序。现在,注意到了一个bug,但在完全随机的间隔内,有时会从错误的租户那里为另一个租户获取数据。
例如,Tenant1登录,但是他们看到来自Tenant2的信息。我正在使用来自所有租户的相同数据库,但使用的是TenantId。
我从Global > Application_AcquireRequestState引导应用程序,如下所示:
namespace MultiTenantV1
{
public class Global : HttpApplication
{
public static OrganizationGlobal Tenant;
void Application_Start(object sender, EventArgs e)
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
UnityWebActivator.Start();
}
void Application_AcquireRequestState(object sender, EventArgs e)
{
// boot application
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
// dependency runner
Tenant = new Tenant().Fetch(context.Request.Url);
// third party api calls
var session = HttpContext.Current.Session;
if (session != null)
{
if (string.IsNullOrEmpty(Session["CountryCode"] as string))
{
string isDevelopmentMode = ConfigurationManager.AppSettings["developmentmode"];
if (isDevelopmentMode == "false")
{
// api call to get country
}
else
{
// defaults
}
}
Tenant.CountryCode = Session["CountryCode"].ToString();
}
}
}
}现在,在整个应用程序中,我使用'Tenant‘对象作为起点,并使用它查询数据库以获取进一步的数据。我注意到,有时租户会看到另一个租户名称(不确定其他数据是否也以相同的方式可见)。
我正在基于HttpContext.Request.Url初始化‘租户’。因此,无法加载其他租户数据。
在上面的代码中,或者在我使用的HttpContext.Request.Url中,有人能看到任何可能导致为任何特定请求提取错误租户的东西吗?
发布于 2016-12-30 09:27:37
每个请求都将覆盖静态租户对象,因此在并发请求时,将使用错误的租户。
关键是在每个请求中存储租户,例如在HttpContext.Current中。我通常使用一个租约解析器,它包含如下代码:
public string CurrentId {
get {
return (string)HttpContext.Current.Items["CurrentTenantId"];
}
set {
string val = value != null ? value.ToLower() : null;
if (!HttpContext.Current.Items.Contains("CurrentTenantId")) {
HttpContext.Current.Items.Add("CurrentTenantId", val);
} else {
HttpContext.Current.Items["CurrentTenantId"] = val;
}
}
}在Application_AcquireRequestState中,我根据url设置CurrentId。
然后,通过获取CurrentId,在需要了解租户的类中使用tenancy算盘。
https://stackoverflow.com/questions/41392424
复制相似问题