在ASP.NET Core的ViewEngineExpander中添加搜索位置

时间:2016-08-07 04:51:56

标签: c# asp.net asp.net-core

我已经阅读了几个教程,解释了在需要移动views文件夹的情况下如何替换 views文件夹的默认路径。但是,我一直在试图弄清楚如何添加视图引擎搜索的路径。

这是我到目前为止所拥有的:

customLoadMoreDataFromApi

在我的 Startup.cs

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
    }
}

2 个答案:

答案 0 :(得分:1)

如果要更改搜索视图的默认行为,请尝试以下操作:

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/"));

}

答案 1 :(得分:0)

这只是扩展了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";
    }
}