如何在自定义剃刀视图引擎中使用相对虚拟路径 [英] How to use relative virtual path in custom razor view engine

查看:104
本文介绍了如何在自定义剃刀视图引擎中使用相对虚拟路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有覆盖的MasterLocationFormats的自定义剃刀视图引擎.我想提供用于搜索视图和母版页的相对虚拟路径位置.

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.

那怎么办?

 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.

示例:

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

这篇关于如何在自定义剃刀视图引擎中使用相对虚拟路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆