Often when building a Web site there is a need to log the HTML of the page that is displayed to the user. This, for example, can be useful for history logging or emailing a copy of the form.
Since I frequently use .NET Webforms it is actually relatively easy to obtain the rendered HTML and store it for future use. Surprisingly there is relatively little information online about how to do this.
How is this done? The key is the page’s Render event. I add a method that overrides the page’s Render event and records the stream as it is sent to the browser. Once the page has been streamed and recorded the result can be saved to the database or stored in the session as you see fit.
Below I will give an example in VB.NET, but the principal is the same in C#:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter) Dim sb As StringBuilder = New StringBuilder() Dim sw As StringWriter = New StringWriter(sb) Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) MyBase.Render(htw) Dim thisPage As String = sb.ToString() writer.Write(thisPage) Session("abc") = thisPage End Sub