@CodingSolution
asp.net core, asp.net mvc6 項目中默認使用Razor ViewEngine,按"約定勝于配置"的原則,默認的項目結(jié)構(gòu)是按Controller, Views, Model這樣的文件結(jié)構(gòu)來組織的,其中。
其中主所有的View放在了Views目錄中。
如果需要改變View的位置,可以通過IViewLocationExpander接口來實現(xiàn)自定義,主要的是就是View的查找路徑。
默認的項目文件結(jié)構(gòu)是
/
/controllers/
/controllers/HomeController.cs
/Models/
/Models/SomeModel.cs
/Views/
/Views/shared/_layout.cshtml
/Views/Home/Index.cshtml
按模塊重新組織后的項目,
/UI/
/UI/HOME/
/UI/HOME/controllers/
/UI/HOME/controllers/HomeController.cs
/UI/HOME/Models/SomeModel.cs
/UI/HOME/Views/Index.cshtml
/UI/SharedViews/_layout.cshtml
解決辦法 就是 通過繼承 IViewLocationExpander 接口,自定義一個View的發(fā)現(xiàn)路徑(假設(shè)名為 MyViewLocationExpander.cs),如下。
public class MyViewLocationExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(
ViewLocationExpanderContext context,
IEnumerable<string> viewLocations)
{
yield return "~/UI/{1}/Views/{0}.cshtml";
yield return "~/UI/{1}/{0}.cshtml";
yield return "~/UI/SharedViews/{0}.cshtml";
}
public void PopulateValues(ViewLocationExpanderContext context)
{
}
然后在 startup.cs 中注冊下
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddMvc()
.AddRazorOptions(razor =>
{
razor.ViewLocationExpanders.Add(new IdSvrHost.UI.MyViewLocationExpander());
});
// ...
}
效果如下

Paste_Image.png