テナントが独自のサブドメインを取得できるマルチテナント アプリを作成しようとしています。
- tenant1.mysite.com
- tenant2.mysite.com
カスタムroutedataを使用してみましたが、最初のページでのみ機能し、/login、/register などの他のページでは常にエラーがスローされ、非常に不可解になります。
あきらめて、ワイルドカード DNS の使用を続行し、サブドメインに基づいてビューをレンダリングする方法を HomeController に決定させました。
アクションフィルター
public class SubdomainTenancy : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string subdomain = filterContext.RequestContext.HttpContext.Request.Params["subdomain"]; // A subdomain specified as a query parameter takes precedence over the hostname.
if (subdomain == null)
{
string host = filterContext.RequestContext.HttpContext.Request.Headers["Host"];
int index = host.IndexOf('.');
if (index >= 0)
subdomain = host.Substring(0, index);
filterContext.Controller.ViewBag.Subdomain = subdomain;
}
base.OnActionExecuting(filterContext);
}
}
ホームコントローラー
[SubdomainTenancy]
[AllowAnonymous]
public class HomeController : BaseController
{
public ActionResult Index()
{
string subdomain = ViewBag.Subdomain;
if (subdomain != "www" && !string.IsNullOrEmpty(subdomain) )
{
var db = new tenantdb();
var store = db.GetBySubdomain(subdomain);
if (store == null)
{
return Redirect(HttpContext.Request.Url.AbsoluteUri.Replace(subdomain, "www"));
}
else //it's a valid tenant, let's see if there's a custom layout
{
//load custom view, (if any?)
}
}
return View();
}
}
VirtualPathProvider を使用してサブドメインに基づいてデータベースからビューを読み込もうとすると問題が発生しますが、おそらくライフサイクルが原因で HttpContext にアクセスできませんか? RazorEngineを使用して(データベースから) カスタム ビューを読み込もうとしました。
最初にデータベースでカスタム ビューを検索し、データベース内のビューを使用してレンダリングする Web アプリでマルチテナンシーをサポートするにはどうすればよいですか?