【发布时间】:2023-04-09 07:21:01
【问题描述】:
我定义了一个自定义 IViewLocationExpander 来检查多租户 Web 应用程序中特定于站点的视图。
假设有两个租户 WebsiteA 和 WebsiteB 以及 HomeController 和 Index 视图的以下文件结构
- 查看次数
- 首页
- 网站A
- Index.cshtml
- Index.cshtml
- 网站A
- 首页
我的 IViewLocationExpander 将为 WebsiteA 呈现 Views/Home/WebSiteA/Index.cshtml 并为 WebsiteB 呈现 Views/Home/Index.cshtml - 因为没有特定的索引视图到 WebsiteB,所以它使用默认的。
我还在 Views 中设置了一个名为“Common”的文件夹来保存任何部分视图 - 想法是我可以以相同的方式呈现自定义的部分视图(例如标题)。
- 查看次数
- 普通
- 网站A
- _Header.cshtml
- _Header.cshtml
- 网站A
- 普通
这是我的 IViewLocationExpander
的代码public sealed class TenantViewLocationExpander : IViewLocationExpander
{
private ITenantService _tenantService;
private string _tenant;
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
string[] locations =
{
"/Views/{1}/" + _tenant + "/{0}.cshtml",
"/Views/Common/" + _tenant + "/{0}.cshtml",
"/Views/Shared/" + _tenant + "/{0}.cshtml",
"/Pages/Shared/" + _tenant + "/{0}.cshtml",
"/Views/{1}/{0}.cshtml",
"/Views/Common/{0}.cshtml",
"/Views/Shared/{0}.cshtml",
"/Pages/Shared/{0}.cshtml"
};
return locations;
}
public void PopulateValues(ViewLocationExpanderContext context)
{
_tenantService = context.ActionContext.HttpContext.RequestServices.GetRequiredService<ITenantService>();
_tenant = _tenantService.GetCurrentTenant();
}
}
一切都适用于标准视图,但是当我尝试渲染部分视图时,我总是会返回默认值(例如,上面示例中的 Views/Common/_Header.cshtml)
我正在像这样在我的布局中渲染部分......
<partial name="_Header.cshtml" />
如果我删除 Views/Common/_Header.cshtml 文件 - 仅保留特定于站点的文件 - 我会收到一个异常,指出无法找到该视图
InvalidOperationException: The partial view '_Header.cshtml' was not found. The following locations were searched:
/Views/Shared/_Header.cshtml
似乎扩展器没有添加到部分视图的额外位置。所以我的问题是,如何配置 IViewLocationExpander 以使用 Partials?
在旧版本的 MVC 中,我看到您可以通过设置 ViewLocationFormats 和 PartialViewLocationFormats 来专门定义它们,但在 MVC Core 中我无法在任何地方看到该选项?
抱歉,如果这在其他地方被掩盖了 - 我无法在任何地方找到答案。
提前致谢!
【问题讨论】:
标签: c# asp.net-core model-view-controller