我通常从 VirtualPathProvider 降级
在这里查看更多信息:
http://coderjournal.com/2009/05/creating-your-first-mvc-viewengine/
然后在启动中注册它:
HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedViewPathProvider());
您不必处理范围之外的路径,因为您可以在基本定义上传递函数,就像我在此嵌入式视图路径提供程序中所做的那样:
public class EmbeddedViewPathProvider: VirtualPathProvider
{
static EmbeddedViewPathProvider()
{
ResourcePaths = new Dictionary<string, ViewResource>();
foreach (var resource in SettingsManager.Get<CoreSettings>().Assemblies.Select(assembly => new ViewResource
{
VirtualPath = "/views/embedded/" + assembly.ToLower(), AssemblyName = assembly
}))
{
AddResource(resource);
}
}
public static void AddResource(ViewResource assemblyResource)
{
ResourcePaths.Add(assemblyResource.VirtualPath, assemblyResource);
}
private static Dictionary<string, ViewResource> ResourcePaths { get; set; }
public bool IsAppResourcePath(string virtualPath)
{
var checkPath = VirtualPathUtility.ToAppRelative(virtualPath).ToLower();
return ResourcePaths.Any(resourcePath => checkPath.Contains(resourcePath.Key) && ResourceExists(resourcePath.Value, checkPath));
}
private static bool ResourceExists(ViewResource assemblyResource, string path)
{
var name = assemblyResource.GetFullyQualifiedTypeFromPath(path);
return Assembly.Load(assemblyResource.AssemblyName).GetManifestResourceNames().Any(s => s.ToLower().Equals(name));
}
public ViewResource GetResource(string virtualPath)
{
var checkPath = VirtualPathUtility.ToAppRelative(virtualPath).ToLower();
return (from resourcePath in ResourcePaths where checkPath.Contains(resourcePath.Key) select resourcePath.Value).FirstOrDefault();
}
public override bool FileExists(string virtualPath)
{
var exists = base.FileExists(virtualPath);
return exists || IsAppResourcePath(virtualPath);
}
public override VirtualFile GetFile(string virtualPath)
{
if (IsAppResourcePath(virtualPath) && !base.FileExists(virtualPath))
{
var resource = GetResource(virtualPath);
return new ViewResourceVirtualFile(virtualPath, resource);
}
return base.GetFile(virtualPath);
}
public override CacheDependency
GetCacheDependency(string virtualPath,
IEnumerable virtualPathDependencies,
DateTime utcStart)
{
if (IsAppResourcePath(virtualPath))
{
return null;
}
var dependencies = virtualPathDependencies.OfType<string>().Where(s => !s.ToLower().Contains("/views/embedded")).ToArray();
return base.GetCacheDependency(virtualPath, dependencies, utcStart);
}
public override string GetCacheKey(string virtualPath)
{
return null;
}
}