生成静态页的三种方法

做网站时,有时为了提高性能,除了使用ASP.Net页面缓存以外,也可以将网站首页生成静态页。

生成静态页面的方法有很多,我们这里就介绍两种:
  1. 模板法
  2. 重写Page的Render方法(该方法来自 "孟子E " )
  3. ASP.Net 2.0中的HttpRequest.SaveAs方法。

1.模板法废话不说,就是经典的实现方法,直接放代码:


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

namespace menutest
{
  /// <summary>
  /// Conn 的摘要说明。
  /// </summary>
  // by kyo
  // 此类是生成静态网页的小程序  
  public class Conn
  {
   public Conn()
   {
   
   }
   public static bool WriteFile(string strText,string strContent,string strAuthor)
   {
    string path = HttpContext.Current.Server.MapPath("/menutest/");
    Encoding code = Encoding.GetEncoding("gb2312");
    // 读取模板文件
    string temp = HttpContext.Current.Server.MapPath("/menutest/news/text.html");
    StreamReader sr=null;
    StreamWriter sw=null;
    string str=""; 
    try
    {
     sr = new StreamReader(temp,code);
     str = sr.ReadToEnd(); // 读取文件
    }
    catch(Exception exp)
    {
     HttpContext.Current.Response.Write(exp.Message);
     HttpContext.Current.Response.End();
     sr.Close();
    }
 
 
    //string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";
    string htmlfilename="kyo.html";
    // 替换内容
    // 这时,模板文件已经读入到名称为str的变量中了
    str = str.Replace("ShowArticle",strText); //模板页中的ShowArticle
    str = str.Replace("biaoti",strText);
    str = str.Replace("content",strContent);
    str = str.Replace("author",strAuthor);
    // 写文件
    try
    {
     sw = new StreamWriter(path + htmlfilename , false, code);
     sw.Write(str);
     sw.Flush();
    }
    catch(Exception ex)
    {
     HttpContext.Current.Response.Write(ex.Message);
     HttpContext.Current.Response.End();
    }
    finally
    {
     sw.Close();
    }
    return true;
   }
  }
}
//原理是利用System.IO中的类读写模板文件,然后用Replace替换掉模板中的标签,写入静态html.
2.重写Render法

函数重载了Page.Render函数,作用是把页面的HTML文本截下来,保存到文件里,进一步的可以去看一下ASP.Net页面生命过程。

代码如下

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("页面生成成功!");
}

将以上上函数数加如到你要生成静太文件的页面里。


3.模板法

在ASP.NET 2.0中,有时候需要对ASP.NET生成的HTML代码进行处理,或者是保存成静态文件。ASP.NET 提供了直接将请求保存成文件的方法:HttpRequest.SaveAs方法。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值