c# - netcore5 视图组件自定义视图搜索路径不适用于区域
问题描述
我已按照此文档查看视图组件:https ://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-5.0#customize-the-view-search-path
但是当我尝试自定义视图搜索路径时它不起作用,我已经使用此配置作为提到的文档:
services.AddMvc()
.AddRazorOptions(options =>
{
options.ViewLocationFormats.Add("/{0}.cshtml");
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
我还尝试了另一种配置:
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationFormats.Add("/{0}" + RazorViewEngine.ViewExtension);
});
但没有任何效果
我只需要将视图组件放在名为 Components 的根文件夹中,并且我的应用程序中有区域,因此每个区域都有其名为 components 的根文件夹
更新
该问题仅出现在区域上,但如文档所述,根目录运行良好
我也尝试过使用此配置,但没有任何效果
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationFormats.Add("/{0}" + RazorViewEngine.ViewExtension);
options.ViewLocationFormats.Add("/Areas/Admin/{0}" + RazorViewEngine.ViewExtension);
});
更新 2
在为区域添加了新的视图位置之后,如前所述,它在区域上不起作用并且搜索到的位置错误不包含我添加的区域的新位置,但是如果您从区域请求视图组件,但如果您从区域请求它,它只会发生root 你会发现搜索到的位置错误包含你添加的区域位置。
如果我从 /Views/Home/Index.cshtml 请求视图组件
搜索的位置将是:
InvalidOperationException:未找到视图“组件/测试/默认”。搜索了以下位置:
/Views/Home/Components/Test/Default.cshtml
/Views/Shared/Components/Test/Default.cshtml
/Pages/Shared/Components/Test/Default.cshtml
/Components/Test/Default.cshtml
/Areas/Admin/Components/Test/Default.cshtml
所以在这里我添加的 2 个位置非常完美!
如果我从 /Areas/Admin/Views/Home/Index.cshtml 请求视图组件
搜索的位置将是:
InvalidOperationException:未找到视图“组件/测试区域/默认”。搜索了以下位置:
/Areas/Admin/Views/Home/Components/TestArea/Default.cshtml
/Areas/Admin/Views/Shared/Components/TestArea/Default.cshtml
/Views/Shared/Components/TestArea/Default.cshtml
/Pages/Shared/Components/TestArea/Default.cshtml
所以这里错过了我添加的 2 个位置!
解决方案
根和区域范围有 2 种不同的视图位置格式配置。使用哪一个取决于代码运行的位置(在搜索视图时)。因此,如果它在根范围内,我们有,RazorViewEngineOptions.ViewLocationFormats
但如果它在区域范围内,我们有RazorViewEngineOptions.AreaViewLocationFormats
.
因此,在您的情况下,您需要添加以下内容:
options.AreaViewLocationFormats.Add("/Areas/Admin/{0}" + RazorViewEngine.ViewExtension);
对于可以应用所有区域的通用格式,我们可以使用{2}
为区域名称设计的占位符,如下所示:
options.AreaViewLocationFormats.Add("/Areas/{2}/{0}" + RazorViewEngine.ViewExtension);
推荐阅读
- selenium - Selenium Grid 和 pytest-xdist 插件有什么区别?
- discord.js - Discord.JS - 如何从用户名中获取用户 ID?
- java - 每 10 分钟检查一次服务器更改并在通知中显示更改
- javascript - 插件仅在单击两次后打开
- visual-studio - 如何从外部键盘获取 F 按钮以在 Visual Studio 上工作
- c++ - odbc 绑定到日期时间列在 Linux 上失败,但在 Windows 上有效
- sql - 如何使用 BigQuery 生成截至当前周的日期数组?
- fiware - helm install Orion Context Broker 的问题
- node.js - 我想在我的“索引”中显示一些延迟的图像
- python - 在 Python.NET 中访问 C# 字典:TypeError:无法将字典更新序列元素 #0 转换为序列