我已按照此文档查看视图组件:https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-5.0#customize-the-view-search-path https://learn.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 的根文件夹
UPDATE
该问题仅出现在区域上,但在根上工作正常,如文档所述
我也尝试过使用此配置但没有任何效果
services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationFormats.Add("/{0}" + RazorViewEngine.ViewExtension);
options.ViewLocationFormats.Add("/Areas/Admin/{0}" + RazorViewEngine.ViewExtension);
});
UPDATE 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:未找到视图“Components/TestArea/Default”。搜索了以下位置:
/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 个位置在这里被遗漏了!