我需要做的是在MVC视图中捕获表达式的结果(下面的示例)。
我还提供了一个存根处理器来演示我想要实现的目标。基本上我想将Action的目标转移到一些我可以稍后操作的任意字符串缓冲区。但是Target属性是只读的。可以使用反射覆盖它,如下所示(将目标设置为其核心具有StringBuffer的任意编写器)。这并没有正常工作,当我执行inline()时,我一直得到一个空引用异常。
有人可以帮忙吗?下面的代码(GetInlineResult
是关键方法)。
查看
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% MvcApplication5.Processor.Absorb(() => {%>
reverse = (string) ->
string.split('').reverse().join ''
alert reverse '.eeffoC yrT'
<%}); %>
<%=MvcApplication5.Processor.Render()%>
</asp:Content>
处理器代码
public class Processor
{
public static void Absorb(Action inline)
{
string input = GetInlineResult(inline);
string output = Process(input);
File.WriteAllText("SOME_PATH", output);
}
private static string Process(string input)
{
string output = input;
/* IRRELEVANT PROCESSING */
return output;
}
private static string GetInlineResult(Action inline)
{
// create writers etc.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htmltw = new HtmlTextWriter(sw);
// set internal value to new writer
FieldInfo fi = inline.GetType().GetField("_target", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(inline, htmltw);
// execute
inline();
// get contents
return sb.ToString();
}
public static string Render()
{
/* GENERATE LINK TO RENDERED FILE <script type="tpl" src="SOME_PATH"> */
return "<script type='tpl' src='SOME_URL'></script>";
}
}
答案 0 :(得分:0)
问题解决了。
我过度思考这个问题并用文本编写器替换生成的视图类,而不是替换视图TextWriter实例。
更新了GetInlineResult(目前处于非常粗略的形式)
private static string GetInlineResult(Action inline)
{
// create writers etc.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htmltw = new HtmlTextWriter(sw);
object view = inline.Target;
FieldInfo field = view.GetType().GetField("__w");
HtmlTextWriter tw = field.GetValue(view) as HtmlTextWriter;
field.SetValue(view, htmltw);
// execute
inline();
field.SetValue(view, tw);
// get contents
return sb.ToString();
}