好消息...在 ASP.NET Core 2 及更高版本中,您不再需要自定义 ViewEngine 甚至 ExpandViewLocations。
使用 OdeToCode.AddFeatureFolders 包
这是最简单的方法... K. Scott Allen 在 OdeToCode.AddFeatureFolders 为您提供了一个 nuget 包,它很干净,并且包含对区域的可选支持。 GitHub:https://github.com/OdeToCode/AddFeatureFolders https://github.com/OdeToCode/AddFeatureFolders
安装软件包,就这么简单:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddFeatureFolders();
...
}
...
}
DIY
如果您需要对文件夹结构进行极其精细的控制,或者如果您出于某种原因不允许/不想获取依赖项,请使用此选项。这也很简单,尽管可能比上面的 nuget 包更混乱:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<RazorViewEngineOptions>(o =>
{
// {2} is area, {1} is controller,{0} is the action
o.ViewLocationFormats.Clear();
o.ViewLocationFormats.Add("/Controllers/{1}/Views/{0}" + RazorViewEngine.ViewExtension);
o.ViewLocationFormats.Add("/Controllers/Shared/Views/{0}" + RazorViewEngine.ViewExtension);
// Untested. You could remove this if you don't care about areas.
o.AreaViewLocationFormats.Clear();
o.AreaViewLocationFormats.Add("/Areas/{2}/Controllers/{1}/Views/{0}" + RazorViewEngine.ViewExtension);
o.AreaViewLocationFormats.Add("/Areas/{2}/Controllers/Shared/Views/{0}" + RazorViewEngine.ViewExtension);
o.AreaViewLocationFormats.Add("/Areas/Shared/Views/{0}" + RazorViewEngine.ViewExtension);
});
...
}
...
}
就是这样!无需特殊课程。
处理 Reshaper/Rider
额外提示:如果您使用 ReSharper,您可能会注意到在某些地方 ReSharper 无法找到您的视图,并会向您发出烦人的警告。要解决这个问题,请引入 Resharper.Annotations 包,并在您的startup.cs(或其他任何地方)中为每个视图位置添加以下属性之一:
[assembly: AspMvcViewLocationFormat("/Controllers/{1}/Views/{0}.cshtml")]
[assembly: AspMvcViewLocationFormat("/Controllers/Shared/Views/{0}.cshtml")]
[assembly: AspMvcViewLocationFormat("/Areas/{2}/Controllers/{1}/Views/{0}.cshtml")]
[assembly: AspMvcViewLocationFormat("/Controllers/Shared/Views/{0}.cshtml")]
希望这能让一些人免受我刚刚经历的沮丧时光的困扰。 :)