在发送给用户之前编辑输出html

时间:2014-02-12 13:16:14

标签: asp.net master-pages

我正在用asp.net创建一个网站。我希望能够在输出发送给用户之前编辑我的母版页,页面和用户控件的html输出。我在互联网上找到了一些功能,允许我通过预渲染功能编辑代码,但它们似乎都不起作用。

我想从我的代码中删除html注释。是否有可能在渲染之前在html上执行一些正则表达式函数?

2 个答案:

答案 0 :(得分:1)

如果您只想在将代码呈现给客户端之前从代码中删除注释,请更改注释方式。使用服务器端评论= <%-- hi --%>

所以这个:

<!-- Don't remove the <p> below because our stupid clients are too stupid to figure out this form without it -->
<p>Tip: The field labeled "First Name" is meant for your first name. Don't type in your last name in this box.</p>
<%-- Don't remove this <p> either because both our clients and our boss are too dumb to figure it out  --%>
<p>Tip 2: Type your last name in the field labeled "Last Name".</p>

将呈现为:

<!-- Don't remove the <p> below because our stupid clients are too stupid to figure out this form without it -->
<p>Tip: The field labeled "First Name" is meant for your first name. Don't type in your last name in this box.</p>

<p>Tip 2: Type your last name in the field labeled "Last Name".</p>


但是,如果您真的需要在全局范围内渲染到客户端之前编辑输出HTML,并且您不能在代码中修复它,则可以在母版页中执行此操作:

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
    StringWriter sw = new StringWriter();
    HtmlTextWriter tw = new HtmlTextWriter(sw);
    base.Render(tw);
    string yourHTML = sw.ToString();
    // do stuff with yourHTML
    writer.Write(yourHTML);
    tw.Dispose();
    sw.Dispose();
}

所以在一个非常简单的示例中,如果你有代码

<h1>I'm a big fat h1</h1>

你可以在那个功能中有:

yourHTML = yourHTML.Replace("<h1>","<h5>");
yourHTML = yourHTML.Replace("</h1>", "</h5>");

现在上面的代码呈现为

<h5>I'm a big fat h1</h5>

要满足非常合理的要求,在将所有h1代码呈现给浏览器之前将其更改为h5

答案 1 :(得分:0)

我认为你要找的是ControlAdapters

我之前使用SharePoint将它们全部用于使输出代码更易于访问。您在WebConfig中注册它们然后传递渲染的控件。此时,您可以使用regext来处理和修改emmited标记