关于如何使剃刀成为现有项目中的默认视图引擎的公认答案只说明了一半。
正如我在问题中建立的那样——我们在项目中确实有剃刀视图——但事实证明,你需要~/Views
在项目中有一个文件夹才能启动这个逻辑。在我们的例子中,我们使用所有 MVC 的区域4+ 代码,所以我们没有费心创建~/Views
文件夹。
我反映了 Asp.Net MVC VS 扩展的“添加视图”对话框 - 在 Microsoft.VisualStudio.Web.Mvc.UserInterface.MvcAddViewDialog.Init
方法中(我添加了对此代码的分析中的注释),您可以找到在首次显示对话框时选择默认视图引擎的代码:
//find the project's Views folder
ProjectItem viewsFolder = MvcProjectUtil.GetViewsFolder(this.Project);
//if not found, or if a view engine is already cached then skip this
if (viewsFolder != null && string.IsNullOrWhiteSpace(viewEngineName))
{
//has razor views?
bool flag = false;
//has webforms views?
bool flag2 = false;
//scan all folders and files in the project, looking at all file extensions
//if .cshtml or .vbhtml are found, then flag==true
//if .aspx are found, then flag2 == true
//both can be true when this method returns.
this.GetViewTypes(viewsFolder.ProjectItems, ref flag, ref flag2);
//if there's at least one razor view, or if there are no webforms views
if (flag || !flag2)
{
//assign either C# or VB razor view type
viewEngineName = ((this.Project.Kind ==
"{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") ? "VBHTML" : "CSHTML");
}
}
//this'll get bound in the combo on the dialog
this.ViewEngineName = viewEngineName;
如您所见,视图类型的扫描仅在~/Views
文件夹上进行 - 它不会费心寻找区域。
我们所要做的就是添加一个空~/Views
文件夹(尽管我们也复制了 Web.Config 以添加 404 处理程序),并且在下一次重新加载项目时,Razor 会在下拉列表中自动选择。这是因为,正如在上述 SO 上接受的答案中正确描述的那样,如果找到剃刀视图或在该文件夹中找不到 webforms 视图,则使用 Razor。