ASP Net Core 视图位置问题

ASP Net Core View Location issue

我一直在尝试在 ASP.Net Core 1.0 中创建一个 MVC 应用程序,并希望我的控制器使用非标准目录中的 *cshtml 文件,比如 "View1"。

这是我在尝试向 View 方法提供位置时看到的错误。

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 GET http://127.0.0.1:8080/  
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
  Executing action method
com.wormhole.admin.Controllers.HomeController.Index (wormhole) with arguments ((null)) - ModelState is Valid
fail: Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor[3]
  The view 'View1/Home/Index.cshtml' was not found. Searched locations: /Views/Home/Index.cshtml
fail: Microsoft.AspNetCore.Server.Kestrel[13]
  Connection id "0HL1GIEMCQK67": An unhandled exception was thrown by the application.
System.InvalidOperationException: The view 'View1/Home/Index.cshtml' was not found. The following locations were searched:
/Views/Home/Index.cshtml

有没有一种方法可以让我轻松地做到这一点并从应用程序中删除旧的视图位置??

仅供参考。 我探索了使用 Areas 的选项,但这并不完全符合我对 App 的要求。

解决方案在this blog post

您可以使用 IViewLocationExpander 界面来定义在何处搜索视图

public class MyViewLocationExpander : IViewLocationExpander
{
    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        yield return "/View1/{1}/{0}.cshtml";
        yield return "/View1/Shared/{0}.cshtml";
    }

    public void PopulateValues(ViewLocationExpanderContext context)
    {            
    }
}

{1}是控制器名,{0}是视图名。您可以发送要搜索的位置列表,也可以根据上下文更改位置。

您需要在 Startup.cs 中注册此 class :

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.Configure<RazorViewEngineOptions>(options => {
            options.ViewLocationExpanders.Add(new MyViewLocationExpander());
        });
    }