获取页面的HTML作为字符串

时间:2014-12-17 20:11:59

标签: c# asp.net

我试图在完成加载时将页面的html作为字符串获取:

    protected void OnPreRenderComplete(object sender, EventArgs e)
    {
        StringWriter strWrt = new StringWriter();
        HtmlTextWriter htmText = new HtmlTextWriter(strWrt);
        base.Render(htmText);
        html = strWrt.GetStringBuilder();
    }

然而,这导致html字符串为空...所以它不拉。我也尝试过渲染:

    protected override void Render(HtmlTextWriter writer)
    {
        StringWriter strWrt = new StringWriter();
        HtmlTextWriter htmText = new HtmlTextWriter(strWrt);
        base.Render(htmText);
        html = strWrt.GetStringBuilder();
    }

但是当我这样做时,页面不会呈现。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为页面没有渲染,因为你没有使用writer参数做任何事情。 你不能只用HtmlTextWriter的每个实例调用Render,所以需要另一种方法......

以下部分 TextWriter 实现允许我捕获html并呈现页面。 可能还有其他Write方法需要重载才能完成解决方案...

...
    protected override void Render(HtmlTextWriter writer)
    {
        var stringWriter = new TextWriterDecorator(writer.InnerWriter);
        writer.InnerWriter = stringWriter;
        base.Render(writer);

        var html = stringWriter.GetStringBuilder();
    }
}

public class TextWriterDecorator : StringWriter
{
    readonly TextWriter writer;

    public TextWriterDecorator(TextWriter writer)
    {
        this.writer = writer;
    }

    public override void Write(char value)
    {
        this.writer.Write(value);
        base.Write(value);
    }

    public override void Write(char[] buffer)
    {
        this.writer.Write(buffer);
        base.Write(buffer);
    }

    public override void Write(char[] buffer, int index, int count)
    {
        this.writer.Write(buffer, index, count);
        base.Write(buffer, index, count);
    }

    public override void Write(string format)
    {
        this.writer.Write(format);
        base.Write(format);
    }
}