【问题标题】:How to get the Layout value of razor files?如何获取剃须刀文件的布局值?
【发布时间】:2014-06-25 09:32:36
【问题描述】:

我正在做一些自定义基础架构,用于为单个视图自动生成特定的包,并且有一个案例我需要在将它们作为文件迭代时获取每个视图的 Layout 值。

我已经尝试过var view = new RazorView(new ControllerContext(), actionView.FullName, null, true, null);,但这是将 LayoutPath 作为输入,如果我为该参数提供 null,它确实会导致 RazorView 的 LayoutPath 属性上出现空字符串,因此它不会解析文件中的值。

是否有任何其他方法可以以类似的方式解决此问题,或者我最好/唯一的选择是仅解析原始文件(和 _ViewStart)的文本?

这仅在应用程序启动时执行一次,因此性能目前不是问题。

【问题讨论】:

    标签: asp.net-mvc razor razor-3


    【解决方案1】:

    好的,经过大量源代码调试和与内部访问修饰符的史诗般的战斗,我有了一个工作解决方案,而无需渲染整个页面。我不希望其他人需要这个,但无论如何:

    var httpContext = new HttpContextWrapper(new HttpContext(new HttpRequest("", "http://dummyurl", ""), new HttpResponse(new StreamWriter(new MemoryStream()))));
    var page = Activator.CreateInstance(BuildManager.GetCompiledType(ReverseMapPath(actionView.FullName))) as WebViewPage;
    
    page.Context = httpContext;
    page.PushContext(new WebPageContext(), new StreamWriter(new MemoryStream()));
    page.Execute();
    
    var layoutFileFullName = page.Layout;
    
    // If page does not have a Layout defined, search for _ViewStart
    if (string.IsNullOrEmpty(layoutFileFullName))
    {
        page.VirtualPath = ReverseMapPath(actionView.FullName);
        var startpage = StartPage.GetStartPage(page, "_ViewStart", new string[] {"cshtml"});
        startpage.Execute();
        layoutFileFullName = startpage.Layout;
    }
    

    多田!

    附言。 ReverseMapPath 是一个任意函数,用于解析完整文件名的相对路径,例如Getting relative virtual path from physical path

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      相关资源
      最近更新 更多