I am trying to download Razor View from a database.
I am following ASP.NET MVC and Virtual Views and VirtualPathProvider in MVC 5 for this.
my code is:
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); }
Act:
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 the virtualPath value is "/Views/Home/Contact.cshtml" , then the method of the FileExists method returns true and the GetFile method .
Case 2:
When the virtualPath value is "~ / Home / Display / ce28bbb6-03cb-4bf4-8820-373890396a90" , then the FileExists method returns true and the GetFile method and the Display action are never called. and result
HTTP Error 404.0 - Not Found The resource you are looking for has been deleted, its name has changed or is temporarily unavailable.
I have no idea about dynamic representation. I just read this article and try to implement it.
Please tell me where I am wrong.
I am using MVC 5 and .NET 4.5
Md.hasanuzzaman
source share