i am using a custom razor view engine with overridden MasterLocationFormats. I want to give relative virtual path locations for searching views and master pages.
How can that be done?
public class ExampleRazorViewEngine : RazorViewEngine
{
/// <summary>
/// Initializes a new instance of the <see cref="ExampleRazorViewEngine"/> class.
/// </summary>
public ExampleRazorViewEngine()
{
ViewLocationFormats = new string[] {
"../../../Views/{1}/{0}.cshtml",
};
MasterLocationFormats = new string[] {
"../../../Views/{1}/{0}.cshtml",
};
PartialViewLocationFormats = new string[] {
"../../../Views/{1}/{0}.cshtml",
};
FileExtensions = new string[] { "cshtml" };
}
Upon doing this it gives below error.
The relative virtual path ..< path >.. is not not allowed here
Suppose your you want to load view files inside Plugins folder in your project directory. then your code look like the example bellow.
Example:
public class PluginViewEngine : RazorViewEngine
{
private List<string> _plugins = new List<string>();
public PluginViewEngine()
{
var plugins = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins")).ToList();
//Load your directory
plugins.ForEach(s =>
{
var di = new DirectoryInfo(s);
_plugins.Add(di.Name);
});
ViewLocationFormats = GetViewLocations();
MasterLocationFormats = GetMasterLocations();
PartialViewLocationFormats = GetViewLocations();
}
public string[] GetViewLocations()
{
var views = new List<string> {
"~/Views/{1}/{0}.cshtml"
};
_plugins.ForEach(plugin =>
views.Add("~/Plugins/" + plugin + "/Views/{1}/{0}.cshtml")
); //Load your view
return views.ToArray();
}
public string[] GetMasterLocations()
{
var masterPages = new List<string> {
"~/Views/Shared/{0}.cshtml"
};
_plugins.ForEach(plugin =>
masterPages.Add("~/Plugins/" + plugin + "/Views/Shared/{0}.cshtml")
);//Load your view
return masterPages.ToArray();
}
}