ASP Net核心视图位置问题

时间:2016-12-30 08:57:50

标签: c# asp.net asp.net-mvc model-view-controller razorengine

我一直在尝试在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

有没有办法可以轻松完成此操作并从应用程序中删除旧的View位置?

FYI。 我已经探索了使用区域的选项,但这并不适合我想要的应用程序。

1 个答案:

答案 0 :(得分:1)

解决方案在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中注册此类:

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