2016-12-30 127 views
1

我一直試圖在ASP.Net Core 1.0中創建一個MVC應用程序,並且希望我的控制器使用來自非標準目錄的* cshtml文件,比如說「View1」。ASP Net Core View問題

這是我在嘗試向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 

有沒有一種方法可以輕鬆地做到這一點,並從應用程序中刪除舊的視圖位置?

僅供參考。 我已經探索了使用區域的選項,但是這並不適合我想從應用程序中獲得的東西。

回答

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()); 
     }); 
    }