When programming with ASP.NET, opening a page usually involves specifying a hyperlink address and calling the specified page file (.html, .aspx) and other methods.
However, if the content of the page file that is about to be opened is dynamically generated in the program or taken out from the table of the database, how do we display the content?
Our most direct idea is to save the content into a web page file and then call it. This method is certainly possible, but it is not the best method because it will generate many temporary files on the Web server that may never be used.
Another best way is to use text format flow to dynamically display page content. For example, there is a page:
…
<iFrame src=""></iframe>
...
You need to use iFrame to open a page, and the content of this page is dynamically generated. We can write an .ashx file (named html.ashx here) to process. The .ashx file implements the IHttpHandler interface class, which can directly generate the data format used by the browser.
html.ashx file content:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.IO;
using System.Web;
public class Handler : IHttpHandler {
public bool IsReusable {
get {
return true;
}
}
public void ProcessRequest (HttpContext context)
{
// Set up the response settings
context.Response.ContentType = "text/html";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BufferOutput = false;
Stream stream = null;
string html = "<html><body>Success: test of txt.ashx</body></html>";
byte[] html2bytes = System.Text.Encoding.ASCII.GetBytes(html);
stream = new MemoryStream(html2bytes);
if (stream == null)
stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes("<html><body>get Nothing!</body></html>"));
//Write text stream to the response stream
const int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int count = stream.Read(buffer, 0, buffersize);
while (count > 0)
{
context.Response.OutputStream.Write(buffer, 0, count);
count = stream.Read(buffer, 0, buffersize);
}
}
}
In the html.ashx file, the string is first converted into a byte array, then the MemoryStream data stream in memory is generated, and finally written to the OutputStream object and displayed.
In this way, we can display the dynamically generated page through <iFrame src="html.ashx"></iframe> and display the web page content of "Success: test of txt.ashx". In the string html = "<html><body>Success: test of txt.ashx</body></html>"; in the html.ashx file, the content of the variable html can be obtained from the database (put an html in advance The file contents are saved in the database).
Author: Zhang Qing ( http://www.why100000.com )