对于我的ASP.NET MVC 4项目,我正在尝试实现一个自定义视图引擎来查找文件夹中存在的"Index.cshtml"视图文件.另外,我为所有未找到的视图路径抛出了404.
当视图文件不存在时,404工作.当视图文件存在时,视图引擎将尝试使用FileExists()函数查找.Mobile.cshtml文件.没有.mobile.cshtml文件,因此它会抛出异常.为什么视图引擎在找到非移动文件后仍然会查找.mobile.cshtml文件?
例如,当视图引擎能够在"〜/ Views/About/History/Index.cshtml"中找到视图路径时,它将尝试查找文件"〜/ Views/About/History/Index.Mobile.cshtml ".下面是我的自定义视图引擎的完整代码.
namespace System.Web.Mvc
{
// Extend where RazorViewEngine looks for view files.
// This looks for path/index.ext file if no path.ext file is found
// Ex: looks for "about/history/index.chstml" if "about/history.cshtml" is not found.
public class CustomViewEngine : RazorViewEngine
{
public BeckmanViewEngine()
{
AreaViewLocationFormats = new[]
{
"~/Areas/{2}/Views/{1}/{0}/Index.cshtml",
};
ViewLocationFormats = new[]
{
"~/Views/{1}/{0}/Index.cshtml",
};
}
// Return 404 Exception if viewpath file in existing path is not found
protected override bool FileExists(ControllerContext …Run Code Online (Sandbox Code Playgroud)