How to capture page output before it is rendered – level 300

If for some reason you need to capture page output either to log it, analyze it or do a global string replace, then you will need to intercept the rendered Html before it makes it to the wire on the way to the client.  Here is a code snippet that will do just that.


protected override void Render(HtmlTextWriter writer)

{


    StringBuilder sb = new StringBuilder();


    HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));


    base.Render(htw);


    writer.Write(sb.ToString());


    Trace.Warn(sb.ToString());


}


The StringBuilder will get the content, and you can do with it what you please.  Then just make sure to call writer.Write( ) to render the final content to the Response stream.