Output ASP.NET Page to HTML

Introduction:

There are various reasons why it would be more appreciative to have the html page to be served to client.

In normal cases we have a web page where the data is retrieved from the database. This data could be huge and may be its not changing frequently too. In such cases is there a need to always make a trip to server to retrieve the data and sent it to the client??

How can this be taken care of. Is it possible to capture the html and save it for later use.

Lets see how this can be done.

Solution:

The appropriate namespaces to be used here would be

System.Net which have classes WebRequest and WebResponse.

  • WebRequest is the abstact base class for the .NET Framework's request/response model for accessing data from the internet and 
  • WebResponse is the abstract base class from which protocol specific response classes are derived.

System.IO which have classes StreamReader and StreamWriter.

  • StreamReader designed for character input in a particular encoding.
  • StreamWriter designed for character output in a particular encoding. 

Code:

C#

WebRequest mywebReq ;
WebResponse mywebResp ;
StreamReader sr ;
string strHTML ;
StreamWriter sw;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
mywebReq = WebRequest.Create("http://www.c-sharpcorner.com/faq.aspx");
mywebResp = mywebReq.GetResponse();
sr =
new StreamReader(mywebResp.GetResponseStream());
strHTML = sr.ReadToEnd();
sw = File.CreateText(Server.MapPath("temp.html"));
sw.WriteLine(strHTML);
sw.Close();
Response.WriteFile(Server.MapPath("temp.html"));
}

VB.NET

Dim mywebReq As WebRequest
Dim mywebResp As WebResponse
Dim sr As StreamReader
Dim strHTML As String
Dim sw As StreamWriter
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Give the Appropriate URL for .aspx page. in this case its http://www.c-sharpcorner.com/faq.aspx
mywebReq = WebRequest.Create("http://www.c-sharpcorner.com/faq.aspx")
mywebResp = mywebReq.GetResponse()
sr =
New StreamReader(mywebResp.GetResponseStream)
strHTML = sr.ReadToEnd
sw = File.CreateText(Server.MapPath("temp.html"))
sw.WriteLine(strHTML)
sw.Close()
Response.WriteFile(Server.MapPath("temp.html"))
End Sub

Note:For creating the file (in above case "temp.html") give appropriate rights (modify and write) to the ASPNET user.

To specify the Encoding specify the second parameter of the StreamReader accordingly

C#

sr = new StreamReader(mywebResp.GetResponseStream(), System.Text.Encoding.ASCII);

VB.NET

sr = New StreamReader(mywebResp.GetResponseStream, System.Text.Encoding.ASCII)

Output of the .aspx and the html generated is shown below:

code35a.jpg

code35b.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all