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();
      }
    }
  }
  else
  {
    // 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", "");
  else
    return html;
}


Sample from HTSM360 Short Application form:

  ///<summary>

  /// Overridden to handle Confirmation of the order by

  /// capturing the HTTP output and emailing it.

  ///</summary>

  ///<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);

    base.Render(hWriter);

    // *** store to a string

    string PageResult = sb.ToString();

    // *** Write it back to the server

    writer.Write(PageResult);

    string ErrorMessage = "";

    if (ValidSubmission)

    {

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

    }

  }

 

 


Links to resources...

http://odetocode.com/Articles/162.aspx

http://bytes.com/forum/thread115349.html

http://forums.asp.net/p/471841/485661.aspx#485661

http://www.velocityreviews.com/forums/t97151-httpresponse-capture-or-redirect-stream.html

Not directly related, but interesting...

http://69.10.233.10/KB/aspnet/fastload.aspx?display=Print

Tags:

[None]

Comments are closed