对于我的ASP.NET MVC 4项目,我试图实现一个自定义视图引擎来查找" Index.cshtml"视图文件(如果文件夹中存在)。另外,我为所有未找到的视图路径抛出了404.
当视图文件不存在时,404可以正常工作。当视图文件存在时,视图引擎将尝试使用FileExists()函数查找.Mobile.cshtml文件。没有.mobile.cshtml文件,因此它会抛出异常。为什么视图引擎在找到非移动文件后仍然会查找.mobile.cshtml文件?
例如,当视图引擎能够在"〜/ Views / About / History / Index.cshtml"中找到视图路径时,它将尝试查找文件"〜/查看/关于/历史/ Index.Mobile.cshtml&#34 ;.以下是我的自定义视图引擎的完整代码。
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 context, string path)
{
if (!base.FileExists(context, path))
{
throw new HttpException(404, "HTTP/1.1 404 Not Found");
}
return true;
}
}
}
答案 0 :(得分:5)
我在MVC 4 source code中挖掘了一些后找到答案。
RazorViewEngine
来自BuildManagerViewEngine
,而这一个轮流来自VirtualPathProviderViewEngine
。
它是VirtualPathProviderViewEngine
实现方法FindView
的那个:
public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (String.IsNullOrEmpty(viewName))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewName");
}
string[] viewLocationsSearched;
string[] masterLocationsSearched;
string controllerName = controllerContext.RouteData.GetRequiredString("controller");
string viewPath = GetPath(controllerContext, ViewLocationFormats, AreaViewLocationFormats, "ViewLocationFormats", viewName, controllerName, CacheKeyPrefixView, useCache, out viewLocationsSearched);
string masterPath = GetPath(controllerContext, MasterLocationFormats, AreaMasterLocationFormats, "MasterLocationFormats", masterName, controllerName, CacheKeyPrefixMaster, useCache, out masterLocationsSearched);
if (String.IsNullOrEmpty(viewPath) || (String.IsNullOrEmpty(masterPath) && !String.IsNullOrEmpty(masterName)))
{
return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched));
}
return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);
}
当视图路径尚未缓存时,那里使用的GetPath
方法将执行类似的操作:
return nameRepresentsPath
? GetPathFromSpecificName(controllerContext, name, cacheKey, ref searchedLocations)
: GetPathFromGeneralName(controllerContext, viewLocations, name, controllerName, areaName, cacheKey, ref searchedLocations);
去那里!有趣的方法是GetPathFromGeneralName
,它是试图为视图构建整个路径并检查该路径是否存在的方法。该方法循环遍历在View Engine中注册的每个视图位置,使用显示模式对当前HttpContext 有效更新视图路径,然后检查已解析的路径是否存在。如果是,则找到视图,分配给结果,缓存并返回结果路径。
private string GetPathFromGeneralName(ControllerContext controllerContext, List<ViewLocation> locations, string name, string controllerName, string areaName, string cacheKey, ref string[] searchedLocations)
{
string result = String.Empty;
searchedLocations = new string[locations.Count];
for (int i = 0; i < locations.Count; i++)
{
ViewLocation location = locations[i];
string virtualPath = location.Format(name, controllerName, areaName);
DisplayInfo virtualPathDisplayInfo = DisplayModeProvider.GetDisplayInfoForVirtualPath(virtualPath, controllerContext.HttpContext, path => FileExists(controllerContext, path), controllerContext.DisplayMode);
if (virtualPathDisplayInfo != null)
{
string resolvedVirtualPath = virtualPathDisplayInfo.FilePath;
searchedLocations = _emptyLocations;
result = resolvedVirtualPath;
ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, AppendDisplayModeToCacheKey(cacheKey, virtualPathDisplayInfo.DisplayMode.DisplayModeId), result);
if (controllerContext.DisplayMode == null)
{
controllerContext.DisplayMode = virtualPathDisplayInfo.DisplayMode;
}
// Populate the cache for all other display modes. We want to cache both file system hits and misses so that we can distinguish
// in future requests whether a file's status was evicted from the cache (null value) or if the file doesn't exist (empty string).
IEnumerable<IDisplayMode> allDisplayModes = DisplayModeProvider.Modes;
foreach (IDisplayMode displayMode in allDisplayModes)
{
if (displayMode.DisplayModeId != virtualPathDisplayInfo.DisplayMode.DisplayModeId)
{
DisplayInfo displayInfoToCache = displayMode.GetDisplayInfo(controllerContext.HttpContext, virtualPath, virtualPathExists: path => FileExists(controllerContext, path));
string cacheValue = String.Empty;
if (displayInfoToCache != null && displayInfoToCache.FilePath != null)
{
cacheValue = displayInfoToCache.FilePath;
}
ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, AppendDisplayModeToCacheKey(cacheKey, displayMode.DisplayModeId), cacheValue);
}
}
break;
}
searchedLocations[i] = virtualPath;
}
return result;
}
你可能已经注意到我还没有谈到一段带有以下评论的代码(为了清晰起见重新格式化):
// Populate the cache for all other display modes.
// We want to cache both file system hits and misses so that we can distinguish
// in future requests whether a file's status was evicted from the cache
// (null value) or if the file doesn't exist (empty string).
那个(和评论下面的代码:))意味着一旦MVC 4找到了View Engine中注册的View Locations的第一个有效路径,它还会检查所有的视图文件未经测试的附加显示模式存在,因此信息可以包含在缓存中(尽管只是针对该视图位置而不是视图引擎中可用的所有位置)。 另请注意,它是如何将lambda传递给每个测试的显示模式以检查该模式的文件是否存在:
DisplayInfo displayInfoToCache = displayMode.GetDisplayInfo(
controllerContext.HttpContext,
virtualPath,
virtualPathExists: path => FileExists(controllerContext, path));
这就解释了为什么当你覆盖FileExists
时,它也会被调用移动视图,即使它已经找到了非移动视图。
在任何情况下,都可以删除显示模式,方法与添加相同:在应用程序启动时更新DisplayModes集合。例如,删除移动显示模式并仅保留默认和非特定模式(您无法清除集合或找不到视图):
...
using System.Web.WebPages;
...
protected void Application_Start()
{
DisplayModeProvider.Instance.Modes.Remove(
DisplayModeProvider.Instance.Modes
.Single(m => m.DisplayModeId == "Mobile"));
相当长的答案,但希望它有意义!
答案 1 :(得分:2)
您是否尝试删除移动版DisplayModeProvider
。您可以通过在Application_Start
中运行以下内容来实现此目的:
var mobileDisplayMode = DisplayModeProvider.Instance.Modes.FirstOrDefault(a => a.DisplayModeId == "Mobile");
if (mobileDisplayMode != null)
{
DisplayModeProvider.Instance.Modes.Remove(mobileDisplayMode);
}
您遇到的问题是预期的行为,因为FindView方法会查询DisplayModeProvider
。