蜗牛,在赛跑

--努力去改变吧
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ASP.NET 生成静态页面的方法(转)

Posted on 2007-03-23 17:24  body  阅读(103)  评论(0编辑  收藏  举报

做网站时,有时为了提高性能会将网站首页生成静态页(当然, Asp.net中页面缓存也是一个不错的选择了
将页面生成静态的方法有多中,据不完全统计有N种(N>1)
呵呵
以下的方法来自 "孟子E " 解释的方法
个人感觉这个办法比较先进.
代码如下

    protected override void Render(HtmlTextWriter writer)
    ...{
        System.IO.StringWriter html = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter tw = new HtmlTextWriter(html);
        base.Render(tw);
        System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("index.html"), false, System.Text.Encoding.Default);
        sw.Write(html.ToString());
        sw.Close();
        tw.Close();
        Response.Write("页面生成成功!");
    }
将以上上函数数加如到你要生成静太文件的页面里,
函数从载了,Render函数 作用是把页面的 html文本截下来,保存到文件里,
进一步的可以去看一下asp.net页面生命过程.


---------------------------------------------------------------------------------------------------------------------------------第二种方法.
1 using System;
 2 using System.Collections;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Web;
 7 using System.Web.SessionState;
 8 using System.Web.UI;
 9 using System.Web.UI.WebControls;
10 using System.Web.UI.HtmlControls;
11 using System.IO;
12 using System.Text;
13
14 namespace menutest
15 {
16  /// <summary>
17  /// Conn 的摘要说明。
18  /// </summary>
19  // by kyo
20  // 此类是生成静态网页的小程序 
21  public class Conn
22  {
23   public Conn()
24   {
25  
26   }
27   public static bool WriteFile(string strText,string strContent,string strAuthor)
28   {
29    string path = HttpContext.Current.Server.MapPath("/menutest/");
30    Encoding code = Encoding.GetEncoding("gb2312");
31    // 读取模板文件
32    string temp = HttpContext.Current.Server.MapPath("/menutest/news/text.html");
33    StreamReader sr=null;
34    StreamWriter sw=null;
35    string str="";
36    try
37    {
38     sr = new StreamReader(temp,code);
39     str = sr.ReadToEnd(); // 读取文件
40    }
41    catch(Exception exp)
42    {
43     HttpContext.Current.Response.Write(exp.Message);
44     HttpContext.Current.Response.End();
45     sr.Close();
46    }
47
48
49    //string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";
50    string htmlfilename="kyo.html";
51    // 替换内容
52    // 这时,模板文件已经读入到名称为str的变量中了
53    str = str.Replace("ShowArticle",strText); //模板页中的ShowArticle
54    str = str.Replace("biaoti",strText);
55    str = str.Replace("content",strContent);
56    str = str.Replace("author",strAuthor);
57    // 写文件
58    try
59    {
60     sw = new StreamWriter(path + htmlfilename , false, code);
61     sw.Write(str);
62     sw.Flush();
63    }
64    catch(Exception ex)
65    {
66     HttpContext.Current.Response.Write(ex.Message);
67     HttpContext.Current.Response.End();
68    }
69    finally
70    {
71     sw.Close();
72    }
73    return true;
74   }
75  }
76 }
77 //原理是利用System.IO中的类读写模板文件,然后用Replace替换掉模板中的标签,写入静态html.