I am trying to load Razor View from database.
I follow ASP.NET MVC and virtual views and VirtualPathProvider in MVC 5 to do that.
my Code :
VirtualPathProvider :
public class DbPathProvider : VirtualPathProvider
{
public override bool FileExists(string virtualPath)
{
var page = FindPage(virtualPath);
if (page == null)
{
return base.FileExists(virtualPath);
}
else
{
return true;
}
}
public override VirtualFile GetFile(string virtualPath)
{
var page = FindPage(virtualPath);
if (page == null)
{
return base.GetFile(virtualPath);
}
else
{
return new DbVirtualFile(virtualPath, page.PageData.ToArray());
}
}
private SiteModel FindPage(string virtualPath)
{
var db = new DatabaseContext();
var page = db.SiteModels.FirstOrDefault(x => x.SiteName == virtualPath);
return page;
}
}
VirtualFile
public class DbVirtualFile : VirtualFile
{
private byte[] data;
public DbVirtualFile(string virtualPath, byte[] data)
: base(virtualPath)
{
this.data = data;
}
public override System.IO.Stream Open()
{
return new MemoryStream(data);
}
}
Global.asax :
protected void Application_Start()
{
HostingEnvironment.RegisterVirtualPathProvider(new DbPathProvider());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Action :
public ActionResult Display(string id)
{
var db = new DatabaseContext();
var site = db.SiteModels.FirstOrDefault(x => x.PageName == id);
if (site == null)
{
return RedirectToAction("Index", "Home");
}
ViewBag.Body = site.PageContent;
return View(System.IO.Path.GetFileNameWithoutExtension(site.SiteName));
}
Data:
Case 1:
When virtualPath value is "/Views/Home/Contact.cshtml" then FileExists method return true and GetFile method is called.
Case 2:
When virtualPath value is "~/Home/Display/ce28bbb6-03cb-4bf4-8820-373890396a90" then FileExists method return true and GetFile method and Display Action is never called. and result is
HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
I have no idea about dynamic view. I just read that two article and try to implement it.
Please tell me where I am doing wrong.
I am using MVC 5 and .NET 4.5