I have read dozens of related threads and made my very simple virtual provider from samples.
But it does not render virtual file stream. just showing plan text.
Here is the output.
@inherits System.Web.Mvc.WebViewPage
@{ViewBag.Title = "Hellow World !";}
<h2>Hellow World !</h2>
There are related threads about this, but they are not saying how they solved it or the solution does not work. I can't find what did I wrong.
- VirtualPathProvider not parsing razor markup
- MVC3 Custom VirtualPathProvider not rendering Razor
- Pulling a View from a database rather than a file
- How to specify route to shared views in MVC3 when using Areas
- ASP.NET MVC load Razor view from database
- How to load views from a Class Library project?
and there are a lot more...
What's wrong ?
Here is my test code. (Global.asax and that's all that I changed.)
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(
new MyProvider());
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
public class MyProvider : VirtualPathProvider
{
public override bool FileExists(string virtualPath)
{
if (Previous.FileExists(virtualPath))
return true;
else
// ~/Infra is the test url
return virtualPath.StartsWith("/Infra") || virtualPath.StartsWith("~/Infra");
}
public override VirtualFile GetFile(string virtualPath)
{
if (Previous.FileExists(virtualPath))
return base.GetFile(virtualPath);
else
return new MyVirtualFile(virtualPath);
}
public class MyVirtualFile : VirtualFile
{
public MyVirtualFile(string virtualPath) : base(virtualPath) { }
public override Stream Open()
{
//Loading stream from seperate dll shows just plain text
//System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(
// System.IO.Path.Combine(HttpRuntime.BinDirectory, "Infra.dll"));
//return assembly.GetManifestResourceStream("Infra.Views.Home.Index.cshtml");
//Changed to string but also it shows plain text.
return new System.IO.MemoryStream(System.Text.ASCIIEncoding.UTF8.GetBytes(
"@inherits System.Web.Mvc.WebViewPage \r\n <h2>Hellow World !</h2>"));
}
}
}