简体   繁体   中英

How to use relative virtual path in custom razor view engine

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM