.Net, ASP.NET, C#, Programming, VB.NET, Web Development

Catch the HTML for an ASP.NET Web Page

Sometimes when you are working with ASP.NET, you’ll want to be able to programmatically capture the HTML that gets output by your .NET code. Here are sample snippets in VB.NET and C# that should give an idea of how this is done.

In an earlier article I covered this same topic, but it is an important one so here is my second take on the subject with sample code now in both VB.NET and C#.

Below are the functions you need to be able to catch and view the HTML that an ASP.NET Web Forms page gets translated into. There is a lot of example code out there that doesn’t work, so these functions should be useful. To get the final HTML output, just put a breakpoint on the final string to view the HTML in Visual Studio, or write out the string to a control on your Web page.

Being able to output the HTML rendered by ASP.NET is especially useful if you are working with modal dialogs which disable the ability to view page source, but can come in handy in a variety of situations. It can even be useful for saving a historical version of the page.

Basically how this works is that once all of your page content is ready to be sent to the user’s browser, we override the default Render method that is responsible for outputting the finished HTML. Then in the overriding method we can catch the stream of HTML content (using a StringWriter and StringBuilder).


Protected Overrides Sub Render(writer As HtmlTextWriter)
Dim sbPageHtml As New StringBuilder()
Dim swPageHtml As New StringWriter(sbPageHtml)
Dim hwPageHtml As New HtmlTextWriter(swPageHtml)
Dim strPageHtml As String = sbPageHtml.ToString()
End Sub


protected override void Render(HtmlTextWriter writer)
StringBuilder sbPageHtml = new StringBuilder();
StringWriter swPageHtml = new StringWriter(sbPageHtml);
HtmlTextWriter hwPageHtml = new HtmlTextWriter(swPageHtml);
string strPageHtml = sbPageHtml.ToString();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s