ASP.NET生成静态页面的代码

第一种方法:向服务器的动态页面发送请求,获取页面的html代码。这种方法缺点显而易见:速度慢。另外如果请求的动态页面有验证控件的话,返回的html页面却无法进行数据验证。但这种方法写起来比较简单。主要代码如下:

view plaincopy to clipboardprint?
#region//生成被请求URL静态页面   
public static void getUrltoHtml(string Url,string Path)//Url为动态页面地址,Path为生成的静态页面   
{   
 try  
 {   
  System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);   
    // Get the response instance.   
  System.Net.WebResponse wResp =wReq.GetResponse();   
    // Get the response stream.   
  System.IO.Stream respStream  = wResp.GetResponseStream();   
    // Dim reader As StreamReader = New StreamReader(respStream)   
  System.IO.StreamReader reader = new System.IO.StreamReader(respStream,System.Text.Encoding.GetEncoding("gb2312"));   
  string str=reader.ReadToEnd();   
  System.IO.StreamWriter sw=new System.IO.StreamWriter(Path,false,System.Text.Encoding.GetEncoding("gb2312"));   
  sw.Write(str);   
  sw.Flush();   
  sw.Close();   
  System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--   
alert('页面生成成功!');   
// --></mce:script>");   
 }   
 catch(System.Exception ex)   
 {   
  System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--   
alert('页面生成失败!"+ex.Message+"');   
// --></mce:script>");   
 }   
}  
#endregion  
#region//生成被请求URL静态页面
public static void getUrltoHtml(string Url,string Path)//Url为动态页面地址,Path为生成的静态页面
{
 try
 {
  System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
    // Get the response instance.
  System.Net.WebResponse wResp =wReq.GetResponse();
    // Get the response stream.
  System.IO.Stream respStream  = wResp.GetResponseStream();
    // Dim reader As StreamReader = New StreamReader(respStream)
  System.IO.StreamReader reader = new System.IO.StreamReader(respStream,System.Text.Encoding.GetEncoding("gb2312"));
  string str=reader.ReadToEnd();
  System.IO.StreamWriter sw=new System.IO.StreamWriter(Path,false,System.Text.Encoding.GetEncoding("gb2312"));
  sw.Write(str);
  sw.Flush();
  sw.Close();
  System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
alert('页面生成成功!');
// --></mce:script>");
 }
 catch(System.Exception ex)
 {
  System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
alert('页面生成失败!"+ex.Message+"');
// --></mce:script>");
 }
}
#endregion

第二种方法:从文件读取模版,替换模版中的参数后输出文件,这种方法的生成速度上比第一种要快许多,而且模版内容可以用工具任意编辑
主要代码:

view plaincopy to clipboardprint?
public class Create   
{   
 public void CreatePage()   
 {   
    
 }   
 public static bool WriteFile(string strText,string strContent,string strAuthor)   
 {   
  string path = HttpContext.Current.Server.MapPath("/test/");//文件输出目录   
  Encoding code = Encoding.GetEncoding("gb2312");   
  // 读取模板文件   
  string temp = HttpContext.Current.Server.MapPath("/template/test.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";//静态文件名   
  
  // 替换内容   
  // 这时,模板文件已经读入到名称为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  
 public class Create
 {
  public void CreatePage()
  {
  
  }
  public static bool WriteFile(string strText,string strContent,string strAuthor)
  {
   string path = HttpContext.Current.Server.MapPath("/test/");//文件输出目录
   Encoding code = Encoding.GetEncoding("gb2312");
   // 读取模板文件
   string temp = HttpContext.Current.Server.MapPath("/template/test.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";//静态文件名

   // 替换内容
   // 这时,模板文件已经读入到名称为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

第三种方法:如果生成的文件数量比较多,第二种方法就要反复读取模版内容,这时可以用第三种方法——直接将你的模版写在代码中:

view plaincopy to clipboardprint?
/// <summary>   
/// 自定义公共函数   
/// </summary>   
public class myfun   
{  
 
 #region//定义模版页   
 public static string SiteTemplate()   
 {   
  string str="";   
  str+="...";//模版页html代码   
  return str;   
 }  
 
 #endregion   
  
 public static bool WriteFile(string strText,string strContent,string strAuthor)   
 {   
  string path = HttpContext.Current.Server.MapPath("/test/");//文件输出目录   
  Encoding code = Encoding.GetEncoding("gb2312");   
  
  StreamWriter sw=null;   
  string str=SiteTemplate();//读取模版页面html代码    
  
  string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";//静态文件名   
  
  // 替换内容   
  str = str.Replace("ShowArticle",strText);   
  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;   
 }   
}  
 /// <summary>
 /// 自定义公共函数
 /// </summary>
 public class myfun
 {

  #region//定义模版页
  public static string SiteTemplate()
  {
   string str="";
   str+="...";//模版页html代码
   return str;
  }

  #endregion

  public static bool WriteFile(string strText,string strContent,string strAuthor)
  {
   string path = HttpContext.Current.Server.MapPath("/test/");//文件输出目录
   Encoding code = Encoding.GetEncoding("gb2312");

   StreamWriter sw=null;
   string str=SiteTemplate();//读取模版页面html代码

   string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";//静态文件名

   // 替换内容
   str = str.Replace("ShowArticle",strText);
   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;
  }
 }

三种方法比较起来生成速度由慢到快,易操作性则由简到繁。还请根据实际情况选择合适的方法。

[  收  集  ] :

view plaincopy to clipboardprint?
protected override void Render(HtmlTextWriter writer)   
{   
    System.IO.StringWriter html = new System.IO.StringWriter();   
    System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);   
    base.Render(tw);   
    System.IO.StreamWriter sw;   
    sw = new System.IO.StreamWriter(Server.MapPath("default.html"), false, System.Text.Encoding.Default);   
    sw.Write(html.ToString());   
    sw.Close();   
    tw.Close();   
    Response.Write(html.ToString());   
}    
protected override void Render(HtmlTextWriter writer)
{
    System.IO.StringWriter html = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);
    base.Render(tw);
    System.IO.StreamWriter sw;
    sw = new System.IO.StreamWriter(Server.MapPath("default.html"), false, System.Text.Encoding.Default);
    sw.Write(html.ToString());
    sw.Close();
    tw.Close();
    Response.Write(html.ToString());
}   

view plaincopy to clipboardprint?
使用ASP.NET生成静态页面的方法有两种,第一种是使用C#在后台硬编码,第二种是读取模板文件,使用字符串替换的方法。第一种方法编码量大,而且维护比较困难。我重点讲解第二种方法。第二种方法的基本思路是:使用DW之类的工具生成一个静态页面模板。读取该模板文件,然后对里面的特殊标记使用真实的数据替换掉,并生成一个HTML文件   
请看代码   
1.C#   
  
using System;   
using System.Collections.Generic;   
using System.Text;   
using System.Xml;   
using System.IO;   
  
namespace htmlWeb   
{   
   public class CreateHtm   
    {   
         
  
       private string fileName;   
  
       public String FileName   
       {   
           get { return fileName; }   
       }   
       /**//// <summary>   
       /// 读取配置文件   
       /// </summary>   
       /// <param name="dirName">配置文件的路径名</param>   
       /// <param name="tag">配置文件中的标签名</param>   
       /// <returns>_replaceStr的长度</returns>   
       private int GetConfig(String dirName, String tag)   
       {   
           XmlDataDocument config = new XmlDataDocument();   
           try  
           {   
               config.Load(dirName);   
           }   
           catch (Exception ex)   
           {   
               throw ex;   
           }   
           XmlNodeList list = config.GetElementsByTagName(tag);   
           return list.Count;   
       }   
        /**//// <summary>   
        ///生成HTML文件   
        /// </summary>   
        /// <param name="configFileName">配置文件的路径名</param>   
        /// <param name="configTag">配置文件中的标签名</param>   
        /// <param name="dir">生成文件所在的文件夹的路径</param>   
       /// <param name="templateFile">模板文件的的路径</param>   
        /// <param name="param">要替换的字符串数组</param>   
        /// <returns>生成的文件名</returns>   
       public void MakeHtml(String configFileName, String configTag, String dir, String templateFile, String[] param)   
       {   
           fileName = null;   
           int count = GetConfig(configFileName, configTag);   
           String[] _replaceStr = new String[count];   
           try  
           {   
               FileStream tFile = File.Open(templateFile, FileMode.Open, FileAccess.Read);   
               StreamReader reader = new StreamReader(tFile, Encoding.GetEncoding("gb2312"));   
               StringBuilder sb = new StringBuilder(reader.ReadToEnd());   
               reader.Close();   
               for (int i = 0; i < count; i++)   
               {   
                   sb.Replace("$repalce[" + i + "]$", param[i]);   
               }   
  
               fileName = DateTime.Now.ToFileTime().ToString() + ".htm";   
  
               FileStream rFile = File.Create(dir+"/" + fileName);   
               StreamWriter writer = new StreamWriter(rFile, Encoding.GetEncoding("gb2312"));   
               writer.Write(sb.ToString());   
               writer.Flush();   
               writer.Close();   
                  
                
  
  
           }   
           catch (Exception ex)   
           {   
               throw ex;   
           }   
  
  
       }   
  
       public void DeleteHtml(String dirName)   
       {   
           File.Delete(dirName);   
       }   
   }   
}   
  
  private int GetConfig(String dirName, String tag) 此方法用于读取配置文件(见后),主要是获得要替换的字符串的个数,在本类同体现为一个字符串数组   
    public void MakeHtml(String configFileName, String configTag, String dir, String templateFile, String[] param) 此方法用于生成静态页面   
51.52行创建一个字符数组,数组长度为配置文件中的节点个数。55-58行读取模板文件,并用读到的模板文件的HTML代码生成一个StringBuilder对象。59-62行使用StringBuilderd对象的repalce()方法替换标记“$repalce[i]$"为真实的数据   
64行生成一个唯一的文件名(防止覆盖)66-70行把新的字符串写到文件中。这样就生成了一个静态文件了。   
下面看一个使用的实例:   
一个文章管理系统,利用这个类来生成静态页面。   
首先,建立一个配置文件 config.xml.此文件告诉使用者每个标记的含义。如下   
<?xml version="1.0" encoding="utf-8" ?>   
<htmlWeb version="1">   
  <config>   
    <article key="0" value="title"/>   
    <article key="1" value="author"/>   
    <article key="2" value="context"/>   
    <aritcle key="3" value="date"/>   
  </config>   
</htmlWeb>    
10这样配置后,类会把标记数组0,1,2,3的位置分别替换为题目,作者,内容,发布日期。   
看模板文件   
 1<head>   
 2<title>模板文件</title>   
 3</head>   
 4<body>   
 5<h1>这是一个简单的HTML页,朋友们可以根据自己的需要重新设计</h1>   
 6<li>标题:$replace[0]$</li>   
 7<li>作者:$replace[1]$</li>   
 8<li>内容:$repalce[2]$</li>   
 9<li>时间:$repalce[3]$</li>   
10</body>使用方法:   
 1using System;   
 2using System.Data;   
 3using System.Configuration;   
 4using System.Web;   
 5using System.Web.Security;   
 6using System.Web.UI;   
 7using System.Web.UI.WebControls;   
 8using System.Web.UI.WebControls.WebParts;   
 9using System.Web.UI.HtmlControls;   
10   
11namespace UseT   
12{   
13    public class Test{   
14       
15     public void main(){        
16     string[] param = new string[4];   
17     param[0] = "测试模板";   
18     param[1] = "农佳捷";   
19     param[2] = "这是一个测试文章";   
20     param[3] = "2007-10-30";   
21        
22     htmlWeb.CreateHtm cs = new htmlWeb.CreateHtm();   
23     cs.MakeHtml("配置文件的路径   
24“, ”article“, ”生成文件的路径“, "模板文件的路径", param)   
25        
26    }   
27    }   
28}   
29只要把相应的参数修改为实际的值,就生成静态文件了。 

posted @ 2011-04-13 09:09  一夜*孤舟  阅读(659)  评论(1编辑  收藏  举报