ASP.NET 2.0 里输出文本格式流
[作者]:菩提树下的杨过 [来源]:互联网 [收录时间]:2007-8-18 15:10:07
<P> 在用 ASP.NET 编程时,打开一个页面一般是通过指定超链接地址,调用指定的页面文件(.html、.aspx)等方法。</P> <P> 但是,如果即将打开的页面文件的内容是在程序中动态生成,或者是从数据库的表里取出的,我们怎么把这些内容展示出来呢?<BR>我们最直接的想法是,把这些内容先保存成网页文件,再调用它。这种方法当然是可以的,但不是最好的方法,因为这样会在 Web 服务器上生成<BR>许多临时文件,这些文件可能永远也用不着了。</P> <P> 另一种最好的方法是利用文本格式流,把页面内容动态地展示出来。例如,有一个页面:</P> <P> ……<BR> <iFrame src=""></iframe><BR> ……</P> <P> 需要用 iFrame 打开一个页面,这个页面的内容是动态生成的。我们可以写一个 .ashx 文件(这里命名为 html.ashx)来处理。.ashx 文件里实现了 IHttpHandler 接口类,可以直接生成浏览器使用的数据格式。</P> <P> html.ashx 文件内容:</P> <P> &lt;%@ WebHandler Language="C#" Class="Handler" %&gt;</P> <P> using System;<BR> using System.IO;<BR> using System.Web;</P> <P> public class Handler : IHttpHandler {</P> <P> public bool IsReusable {<BR> get {<BR> return true;<BR> }<BR> }</P> <P> public void ProcessRequest (HttpContext context)<BR> {<BR> // Set up the response settings<BR> context.Response.ContentType = "text/html";<BR> context.Response.Cache.SetCacheability(HttpCacheability.Public);<BR> context.Response.BufferOutput = false;</P> <P> Stream stream = null;</P> <P> string html = "<html><body>成功: test of txt.ashx</body></html>";<BR> byte[] html2bytes = System.Text.Encoding.ASCII.GetBytes(html);</P> <P> stream = new MemoryStream(html2bytes);</P> <P> if (stream == null)<BR> stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes("<html><body>get Nothing!</body></html>"));</P> <P> //Write text stream to the response stream<BR> const int buffersize = 1024 * 16;<BR> byte[] buffer = new byte[buffersize];<BR> int count = stream.Read(buffer, 0, buffersize);<BR> while (count > 0)<BR> {<BR> context.Response.OutputStream.Write(buffer, 0, count);<BR> count = stream.Read(buffer, 0, buffersize);<BR> }<BR> }</P> <P> }</P> <P> html.ashx 文件中首先把 string 字符串转化为字节(byte)数组,然后再生成内存中的 MemoryStream 数据流,最后写到 OutputStream 对象中,显示出来。</P> <P> 这样以来,我们就可以通过 <iFrame src="html.ashx"></iframe> 来展示动态生成的页面,显示“成功: test of txt.ashx”的网页内容。html.ashx 文件中 string html = "<html><body>成功: test of txt.ashx</body></html>"; 一句中,变量 html 的内容完全可以从数据库中得到(事先把一个 html 文件内容保存在数据库中)。 </P> <P> 作者: 张庆 (http://www.why100000.com)<BR></P>