以字符串形式获取页面的 HTML
本文关键字:HTML 获取 字符串 | 更新日期: 2023-09-27 18:34:28
我正在尝试在完成加载时将页面的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();
}
但是当我这样做时,页面不会呈现。我做错了什么?
我认为页面没有呈现,因为您没有对 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);
}
}