【问题标题】:asp.net core mvc, finding correct _layout location when using custom location formatasp.net core mvc,使用自定义位置格式时找到正确的 _layout 位置
【发布时间】:2023-03-16 06:33:01
【问题描述】:

在 Controllers 文件夹中,我创建了一个“Profile”子文件夹 (/Controllers/Profile),并使用下面的代码将 /Views/Profile/{controller}/{action} 添加到 View Location Formats。

services.Configure<RazorViewEngineOptions>(options =>
{
    options.ViewLocationFormats.Add("/Views/Profile/{1}/{0}" + RazorViewEngine.ViewExtension);
});

现在我想对所有配置文件页面使用相同的布局,并且我希望它是 /Views/Profile/_layout.cshtml,但除非我将它放在特定的控制器文件夹中,否则它不会被识别。

有没有办法让每个视图在检查 /Views/Shared 之前在其父目录中查找 _layout?

【问题讨论】:

    标签: asp.net-mvc asp.net-core


    【解决方案1】:
    services.Configure<RazorViewEngineOptions>(options =>
    {
        options.ViewLocationFormats.Insert(0, "/Views/Profile/{1}/{0}" + RazorViewEngine.ViewExtension);
        options.ViewLocationFormats.Insert(0, "/Views/Profile/{0}" + RazorViewEngine.ViewExtension);
    });
    

    有两件事使这项工作奏效。 我也添加了“/Views/Profile/{0}”并且还使用了.Insert(index, item) 而不是.Add(item),这样这些位置将在默认位置之前被检查。

    但这不是问题的一般解决方案,这只适用于我插入的文件夹。我相信有更好的方法使用 IViewLocationExpander 和命名空间,比如OdeToCode.AddFeatureFolders

    如果有人知道如何使用 IViewLocationExpander(或了解 OdeToCode.AddFeatureFolders 源代码),那么如果他们能提供通用解决方案,那就太好了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多