我通常是從的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;
}
}
這似乎表明,我要創建一個從的VirtualPathProvider繼承的自定義視圖引擎,但我用的剃鬚刀,所以我有點不清楚如何做到這一點的工作。您提供的鏈接似乎解決了與您描述的情況稍有不同的情況。你能詳細解釋一下嗎?謝謝 – sydneyos 2011-06-17 21:54:37
所以,我將此標記爲答案,雖然這有點誤導(即鏈接)。似乎答案是創建一個從VirtualPathProvider繼承的類,然後按照說明在啓動時註冊它。我沒有這樣做,因爲它基本上攔截了每個路徑請求,你必須重寫和實現你自己的邏輯。這只是爲了方便我在一個地方看到我的所有觀點而開銷太多。希望有一種更簡單的方法來配置默認路徑提供程序。唉。 – sydneyos 2011-06-28 01:33:32
已經添加了代碼來演示如何以嵌入式視圖爲例,但是如果在路徑中找不到,則可以傳遞給基類。 – Richard 2011-06-28 08:12:48