在用 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 文件內容保存在數據庫中)。
新聞熱點
疑難解答
圖片精選