如何获取剃刀文件的布局值?

时间:2014-06-25 09:32:37

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

我正在为自己生成单个视图的特定包做一些自定义基础结构,并且我需要为每个视图获取Layout值,同时将它们作为文件进行迭代。

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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