0

テナントが独自のサブドメインを取得できるマルチテナント アプリを作成しようとしています。

  • 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 アプリでマルチテナンシーをサポートするにはどうすればよいですか?

4

1 に答える 1

1

カスタム ViewEngine を作成し、アプリのマルチテナントを認識させることで、同様のことを行いました... ViewEngine は、サブドメインに基づいてビューを探すことができます (この場合は物理的ですが、db からのものである可能性があります)。

ViewEngine に RazorViewEngine を継承させ、必要に応じてメソッドをオーバーライドしました (FileExists、FindPartialView、FindView)。

カスタム ViewEngine を作成したら、他の ViewEngine をクリアし、global.asax の application_start にカスタム ViewEngine を登録しました。

ViewEngines.Engines.Clear()
ViewEngines.Engines.Add(new CustomViewEngine()) 

カスタム ViewEngine で共有できるサンプル コードはありませんが、これが正しい方向に向けられることを願っています。

于 2014-07-06T02:29:55.070 に答える