在用 ASP.NET 編程時,開啟一個頁面一般是通過指定超連結位址,調用指定的分頁檔(.html、.aspx)等方法。
但是,如果即將開啟的分頁檔的內容是在程式中動態產生,或者是從資料庫的表裡取出的,我們怎麼把這些內容展示出來呢?
我們最直接的想法是,把這些內容先儲存成網頁檔案,再調用它。這種方法當然是可以的,但不是最好的方法,因為這樣會在 Web 服務器上產生
許多臨時檔案,這些檔案可能永遠也用不著了。
另一種最好的方法是利用文字格式設定流,把頁面內容動態地展示出來。例如,有一個頁面:
……
<iFrame src=""></iframe>
……
需要用 iFrame 開啟一個頁面,這個頁面的內容是動態產生的。我們可以寫一個 .ashx 檔案(這裡命名為 html.ashx)來處理。.ashx 檔案裡實現了 IHttpHandler 介面類,可以直接產生瀏覽器使用的資料格式。
html.ashx 檔案內容:
<%@ 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>成功: 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);
}
}
}
html.ashx 檔案中首先把 string 字串轉化為位元組(byte)數組,然後再產生記憶體中的 MemoryStream 資料流,最後寫到 OutputStream 對象中,顯示出來。
這樣以來,我們就可以通過 <iFrame src="html.ashx"></iframe> 來展示動態產生的頁面,顯示“成功: test of txt.ashx”的網頁內容。html.ashx 檔案中 string html = "<html><body>成功: test of txt.ashx</body></html>"; 一句中,變數 html 的內容完全可以從資料庫中得到(事先把一個 html 檔案內容儲存在資料庫中)。
作者: 張慶 (http://www.why100000.com)
2007-5-16