问题
I tried to create a VirtualPathProvider
and set the view as an embedded resource.
class AssemblyResourceVirtualFile : VirtualFile
{
string path;
public AssemblyResourceVirtualFile(string virtualPath)
: base(virtualPath)
{
path = VirtualPathUtility.ToAppRelative(virtualPath);
}
public override System.IO.Stream Open()
{
string[] parts = path.Split('/');
string assemblyName = parts[2];
string resourceName = parts[3];
assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);
var assembly = Assembly.LoadFile(assemblyName);
if (assembly != null)
{
return assembly.GetManifestResourceStream(resourceName);
}
return null;
}
}
And
public class AssemblyResourceProvider : System.Web.Hosting.VirtualPathProvider
{
public AssemblyResourceProvider() { }
private bool IsAppResourcePath(string virtualPath)
{
String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
return checkPath.StartsWith("~/App_Resource/", StringComparison.InvariantCultureIgnoreCase);
}
public override bool FileExists(string virtualPath)
{
return (IsAppResourcePath(virtualPath) ||
base.FileExists(virtualPath));
}
public override VirtualFile GetFile(string virtualPath)
{
if (IsAppResourcePath(virtualPath))
return new AssemblyResourceVirtualFile(virtualPath);
else
return base.GetFile(virtualPath);
}
public override CacheDependency GetCacheDependency(string virtualPath,
IEnumerable virtualPathDependencies, DateTime utcStart)
{
if (IsAppResourcePath(virtualPath))
return null;
else
return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
}
}
My controller
return View("~/App_Resource/Blog.DLL/Blog.Views.Blog.Latest.cshtml");
It does find the view, but I end up getting this error:
... view.cshtml' must derive from WebViewPage, or WebViewPage<TModel>.
When trying to show the partial view using:
@{ Html.RenderAction("Latest", "Blog"); }
Is there a way to fix it?
Or is there an easier way to store views on a DLL?
回答1:
The reason this happens is because you are now serving the razor views from unknown locations the standard ~/views/web.config
no longer applies. So you could put a @inherits System.Web.Mvc.WebViewPage
inside your custom views but it could be quite a hassle.
You may checkout the following article.
来源:https://stackoverflow.com/questions/5467227/how-to-load-views-from-a-class-library-project