ASP.NET 2.0 裡輸出文字格式設定流

來源:互聯網
上載者:User

        在用 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.