I am using a VirtualPathProvider to load razor views from the database as discussed in this article.
The problem is when the view loads, the Razor markup is not being parsed. It is being rendered on the page exactly like this "@inherits System.Web.Mvc.WebViewPage hello world
"
For this example, i have hard-coded the string to be returned by the GetContent()
method.
Here is my code:
public class MvcVirtualPathProvider : VirtualPathProvider {
// virtualPath example >> "~/Views/View/21EC2020-3AEA-1069-A2DD-08002B30309D.cshtml"
private static bool IsPathVirtual(string virtualPath)
{
string path = VirtualPathUtility.ToAppRelative(virtualPath);
// returns true if the path is requested by the "ViewController" controller
if (path.StartsWith("~/Views/TextualReporting/db/", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
return false;
}
public override bool FileExists(string virtualPath) {
if (IsPathVirtual(virtualPath)) {
SimpleVirtualFile file = (SimpleVirtualFile)GetFile(virtualPath);
if (file.Exists) {
return true;
}
return false;
}
return Previous.FileExists(virtualPath);
}
public override VirtualFile GetFile(string virtualPath) {
if (IsPathVirtual(virtualPath)) {
return new SimpleVirtualFile(virtualPath);
}
return Previous.GetFile(virtualPath);
}
// Simply return the virtualPath on every request.
public override string GetFileHash(string virtualPath, System.Collections.IEnumerable virtualPathDependencies) {
if (IsPathVirtual(virtualPath)) {
return virtualPath;
}
return base.GetFileHash(virtualPath, virtualPathDependencies);
}
private class SimpleVirtualFile : VirtualFile {
private string content;
public bool Exists {
get { return (content != null); }
}
public SimpleVirtualFile(string virtualPath)
: base(virtualPath) {
GetContent();
}
public override Stream Open() {
ASCIIEncoding encoding = new ASCIIEncoding();
return new MemoryStream(encoding.GetBytes(this.content), false);
}
protected void GetContent() {
if (IsPathVirtual(VirtualPath)) {
this.content = "@inherits System.Web.Mvc.WebViewPage \r\n hello world";
}
}
}
// just implement the default override and return null if the path is a Virtual Path
public override CacheDependency GetCacheDependency(string virtualPath,
System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart) {
if (IsPathVirtual(virtualPath)) {
return null;
}
return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
}
}