Adding a search location in ASP.NET Core's ViewEngineExp
本文关键字:ViewEngineExp Core NET search location in ASP Adding | 更新日期: 2023-09-27 18:01:06
我读过几篇教程,解释了在需要移动视图文件夹的情况下,如何替换视图文件夹的默认路径。然而,我一直在试图找出如何添加视图引擎搜索的路径。
到目前为止,我拥有的是:
public class BetterViewEngine : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context)
{
}
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
return viewLocations.Select(s => s.Add("")); //Formerly s.Replace("oldPath", "newPath" but I wish to add
}
}
在我的Startup.cs中
services.AddMvc().AddRazorOptions(options =>
{
options.ViewLocationExpanders.Add(new BetterViewEngine());
});
如果您想更改搜索视图的默认行为,请尝试以下操作:
public class BetterViewEngine : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context)
{
context.Values["customviewlocation"] = nameof(BetterViewEngine);
}
public IEnumerable<string> ExpandViewLocations(
ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
return new[]
{
"/folderName/{1}/{0}.cshtml",
"/folderName/Shared/{0}.cshtml"
};
}
}
但如果你只想重命名其中一个文件夹,试试这个:
public IEnumerable<string> ExpandViewLocations(
ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
// Swap /Shared/ for /_Shared/
return viewLocations.Select(f => f.Replace("/Shared/", "/_Shared/"));
}
这只是对Sirwan的答案的扩展,因为在阅读了他的答案的第一部分后,我花了一分钟的时间来弄清楚我需要做什么:
public class ViewLocationRemapper : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
return new[]
{
"/Views/{1}/{0}.cshtml",
"/Views/Shared/{0}.cshtml",
"/Views/" + context.Values["admin"] + "/{1}/{0}.cshtml"
};
}
public void PopulateValues(ViewLocationExpanderContext context)
{
context.Values["admin"] = "AdminViews";
}
}