当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.NET 2.0 里输出文本格式流

ASP.NET
Check if a File is in Internet Explorers Cache
如何检测电脑是否安装了.net framework
[Regex]Greta不支持“Named Groups”特性
使用子類化的方法來實現VB對特殊消息的響應
C#软件启动设计
C#中虛函數,抽象,接口的簡單説明
TreeView的操作
InteliIM 3.0 will be released soon!
如何將 Visual Basic 與 ADO 搭配使用
建立永遠停留在最上層的窗口(VB)
C#中比较两个值型一维数组变量是否值相等
谈谈软件工程设计的艺术
批量添加Active Directory帐号
文件搜索的实现(深度搜索)
一个图形分割问题[答网友]
XML反串行化Namespace不统一而引起的错误
使用Javascript创建XML文件
突破MsComm控件RThreshold限制,全部数据统统收!
如何制作一个带启动屏幕的窗体
【翻译】Managed DirectX(第五章)

ASP.NET 2.0 里输出文本格式流


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 198 ::
收藏到网摘: n/a

在用 ASP.NET 编程时,打开一个页面一般是通过指定超链接地址,调用指定的页面文件(.html、.aspx)等方法。

但是,如果即将打开的页面文件的内容是在程序中动态生成,或者是从数据库的表里取出的,我们怎么把这些内容展示出来呢?
我们最直接的想法是,把这些内容先保存成网页文件,再调用它。这种方法当然是可以的,但不是最好的方法,因为这样会在 Web 服务器上生成
许多临时文件,这些文件可能永远也用不着了。

另一种最好的方法是利用文本格式流,把页面内容动态地展示出来。例如,有一个页面:

需要用 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 文件内容保存在数据库中)。