我不知道您是否已经走得太远而无法考虑其他方法,但我也正在开发一个多租户系统,并且我通过覆盖基于 Razor 的视图引擎来完成它.
public class MultiTenancyRazorViewEngine : RazorViewEngine
{
/// <summary>
/// Finds the specified partial view by using the specified controller context.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="partialViewName">The name of the partial view.</param>
/// <param name="useCache">true to use the cached partial view.</param>
/// <returns>The partial view.</returns>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="controllerContext"/> parameter is null (Nothing in Visual Basic).</exception>
/// <exception cref="T:System.ArgumentException">The <paramref name="partialViewName"/> parameter is null or empty.</exception>
public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
var searchedLocations = new List<string>();
var foundFile = Support.ResolvePath(string.Format("{0}.cshtml", partialViewName), controllerContext.HttpContext, controllerContext.RouteData, searchedLocations);
return foundFile == null
? new ViewEngineResult(searchedLocations)
: base.FindPartialView(controllerContext, foundFile, useCache);
}
/// <summary>
/// Finds the view.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="viewName">Name of the view.</param>
/// <param name="layoutPath">The layout path.</param>
/// <param name="useCache">if set to <c>true</c> [use cache].</param>
/// <returns></returns>
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string layoutPath, bool useCache)
{
var searchedLocations = new List<string>();
var foundFile = Support.ResolvePath(string.Format("{0}.cshtml", viewName), controllerContext.HttpContext, controllerContext.RouteData, searchedLocations);
return foundFile == null
? new ViewEngineResult(searchedLocations)
: base.FindView(controllerContext, foundFile, layoutPath, useCache);
}
我有自己的查找视图的支持方法:“ResolvePath”。我使用 HttpContext 存储正在访问的站点(通过主机名),并根据该主机名(或客户端的唯一 ID)缓存结果。它还允许我使用自己的路径形式来搜索视图,因此我可以:
如果我想覆盖视图的一部分,Views/Controller/Action.cshtml 或 Views/Custom/[client]/Controller/Action.cshtml(或非常小的部分)。
抱歉,它并没有真正回答您的具体问题,但它有帮助吗?如果您对这种方法感兴趣,我可以提供更多代码。