Cavanaugh Richards Cavanaugh Richards - 3 months ago 15
ASP.NET (C#) Question

Adding a search location in ASP.NET Core's ViewEngineExpander

I've read several tutorials that explain how to replace the default path to the views folder in the case that the views folder needs to be moved. However, I've been trying to figure out how to add a path that is searched by the view engine.

Here's what I have so far:

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


And in my Startup.cs

services.AddMvc().AddRazorOptions(options =>
{
options.ViewLocationExpanders.Add(new BetterViewEngine());
});

Answer

If you want to change default behavior for searching the views, try this:

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

But if you just want to rename one of the folders try this:

public IEnumerable<string> ExpandViewLocations(
      ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{

      // Swap /Shared/ for /_Shared/
      return viewLocations.Select(f => f.Replace("/Shared/", "/_Shared/"));

}