Joseph Michael Pesch
VP Programming

ASP.Net Capturing HTML Stream

by 20. August 2008 23:31

Capture the stream during render...

protected override void Render(HtmlTextWriter output) {
    if ( (HasControls()) && (Controls[0] is LiteralControl) ) {
        output.Write("<H2>Your Message: " + ((LiteralControl) Controls[0]).Text + "</H2>");

Generic code for ASP.Net web site...

The code below also demonstrates accessing web page context (things such as Server, Request, Response, etc.) from an external class (e.g. from a class that is being called by a web page) by using the System.Web.HttpContext.Current.

public static string ReadHtmlPage(string URL, bool RemoveTextLineFeeds)
  string html = "";
  if (URL.StartsWith("http"))
    // For external http requests we need to use an actual http request.
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
    using (Stream stream = request.GetResponse().GetResponseStream())
      using (StreamReader reader = new StreamReader(stream))
        html = reader.ReadToEnd();
    // For non-http (i.e. internal) requests we assume a Server.Execute() will be appropriate.
    System.IO.StringWriter writer = new System.IO.StringWriter();
    System.Web.HttpContext.Current.Server.Execute(URL, writer);
    html = writer.ToString();
  // When reading back the html into a string, it seems to typically have \r\n representation of line feeds that we can safely remove.
  if (RemoveTextLineFeeds)
    return html.Replace("\r\n", "");
    return html;

Sample from HTSM360 Short Application form:


  /// Overridden to handle Confirmation of the order by

  /// capturing the HTTP output and emailing it.


  ///<param name="writer"></param>

  protected override void Render(HtmlTextWriter writer)


    // *** Write the HTML into this string builder

    StringBuilder sb = new StringBuilder();

    StringWriter sw = new StringWriter(sb);

    HtmlTextWriter hWriter = new HtmlTextWriter(sw);


    // *** store to a string

    string PageResult = sb.ToString();

    // *** Write it back to the server


    string ErrorMessage = "";

    if (ValidSubmission)


      HowToTorial.Mail.SendMail("Sender", "Sender", "Receiver", "Short Application", true, PageResult, ref ErrorMessage);





Links to resources...

Not directly related, but interesting...



Comments are closed