您的位置:首页 > 编程语言 > ASP

asp.net 生成静态页面的三种方式优劣

2011-04-04 11:24 387 查看
第一种方法:向服务器的动态页面发送请求,获取页面的html代码。这种方法缺点显而易见:速度慢。另外如果请求的动态页面有验证控件的话,返回的html页面却无法进行数据验证。但这种方法写起来比较简单。主要代码如下:
01.#region//生成被请求URL静态页面
02.public static void getUrltoHtml(string Url,string Path)//Url为动态页面地址,Path为生成的静态页面
03.{
04. try
05. {
06. System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
07. // Get the response instance.
08. System.Net.WebResponse wResp =wReq.GetResponse();
09. // Get the response stream.
10. System.IO.Stream respStream = wResp.GetResponseStream();
11. // Dim reader As StreamReader = New StreamReader(respStream)
12. System.IO.StreamReader reader = new System.IO.StreamReader(respStream,System.Text.Encoding.GetEncoding("gb2312"));
13. string str=reader.ReadToEnd();
14. System.IO.StreamWriter sw=new System.IO.StreamWriter(Path,false,System.Text.Encoding.GetEncoding("gb2312"));
15. sw.Write(str);
16. sw.Flush();
17. sw.Close();
18. System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
19.alert('页面生成成功!');
20.// --></mce:script>");
21. }
22. catch(System.Exception ex)
23. {
24. System.Web.HttpContext.Current.Response.Write("<mce:script type="text/javascript"><!--
25.alert('页面生成失败!"+ex.Message+"');
26.// --></mce:script>");
27. }
28.}
29.#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

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

01.public class Create
02.{
03. public void CreatePage()
04. {
05.
06. }
07. public static bool WriteFile(string strText,string strContent,string strAuthor)
08. {
09. string path = HttpContext.Current.Server.MapPath("/test/");//文件输出目录
10. Encoding code = Encoding.GetEncoding("gb2312");
11. // 读取模板文件
12. string temp = HttpContext.Current.Server.MapPath("/template/test.html");//模版文件
13. StreamReader sr=null;
14. StreamWriter sw=null;
15. string str="";
16. try
17. {
18. sr = new StreamReader(temp,code);
19. str = sr.ReadToEnd(); // 读取文件
20. }
21. catch(Exception exp)
22. {
23. HttpContext.Current.Response.Write(exp.Message);
24. HttpContext.Current.Response.End();
25. sr.Close();
26. }
27.
28.
29. string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";//静态文件名
30.
31. // 替换内容
32. // 这时,模板文件已经读入到名称为str的变量中了
33. str = str.Replace("ShowArticle",strText); //模板页中的ShowArticle
34. str = str.Replace("biaoti",strText);
35. str = str.Replace("content",strContent);
36. str = str.Replace("author",strAuthor);
37. // 写文件
38. try
39. {
40. sw = new StreamWriter(path + htmlfilename , false, code);
41. sw.Write(str);
42. sw.Flush();
43. }
44. catch(Exception ex)
45. {
46. HttpContext.Current.Response.Write(ex.Message);
47. HttpContext.Current.Response.End();
48. }
49. finally
50. {
51. sw.Close();
52. }
53. return true;
54. }
55.}
56.
57./原理是利用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

第三种方法:如果生成的文件数量比较多,第二种方法就要反复读取模版内容,这时可以用第三种方法——直接将你的模版写在代码中:
01./// <summary>
02./// 自定义公共函数
03./// </summary>
04.public class myfun
05.{
06.
07. #region//定义模版页
08. public static string SiteTemplate()
09. {
10. string str="";
11. str+="...";//模版页html代码
12. return str;
13. }
14.
15. #endregion
16.
17. public static bool WriteFile(string strText,string strContent,string strAuthor)
18. {
19. string path = HttpContext.Current.Server.MapPath("/test/");//文件输出目录
20. Encoding code = Encoding.GetEncoding("gb2312");
21.
22. StreamWriter sw=null;
23. string str=SiteTemplate();//读取模版页面html代码
24.
25. string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";//静态文件名
26.
27. // 替换内容
28. str = str.Replace("ShowArticle",strText);
29. str = str.Replace("biaoti",strText);
30. str = str.Replace("content",strContent);
31. str = str.Replace("author",strAuthor);
32. // 写文件
33. try
34. {
35. sw = new StreamWriter(path + htmlfilename , false, code);
36. sw.Write(str);
37. sw.Flush();
38. }
39. catch(Exception ex)
40. {
41. HttpContext.Current.Response.Write(ex.Message);
42. HttpContext.Current.Response.End();
43. }
44. finally
45. {
46. sw.Close();
47. }
48. return true;
49. }
50.}
/// <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;
}
}

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

[ 收 集 ] :

01.protected override void Render(HtmlTextWriter writer)
02.{
03. System.IO.StringWriter html = new System.IO.StringWriter();
04. System.Web.UI.HtmlTextWriter tw = new System.Web.UI.HtmlTextWriter(html);
05. base.Render(tw);
06. System.IO.StreamWriter sw;
07. sw = new System.IO.StreamWriter(Server.MapPath("default.html"), false, System.Text.Encoding.Default);
08. sw.Write(html.ToString());
09. sw.Close();
10. tw.Close();
11. Response.Write(html.ToString());
12.}
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());
}

01.使用ASP.NET生成静态页面的方法有两种,第一种是使用C#在后台硬编码,第二种是读取模板文件,使用字符串替换的方法。第一种方法编码量大,而且维护比较困难。我重点讲解第二种方法。第二种方法的基本思路是:使用DW之类的工具生成一个静态页面模板。读取该模板文件,然后对里面的特殊标记使用真实的数据替换掉,并生成一个HTML文件
02.请看代码
03.1.C#
04.
05.using System;
06.using System.Collections.Generic;
07.using System.Text;
08.using System.Xml;
09.using System.IO;
10.
11.namespace htmlWeb
12.{
13. public class CreateHtm
14. {
15.
16.
17. private string fileName;
18.
19. public String FileName
20. {
21. get { return fileName; }
22. }
23. /**//// <summary>
24. /// 读取配置文件
25. /// </summary>
26. /// <param name="dirName">配置文件的路径名</param>
27. /// <param name="tag">配置文件中的标签名</param>
28. /// <returns>_replaceStr的长度</returns>
29. private int GetConfig(String dirName, String tag)
30. {
31. XmlDataDocument config = new XmlDataDocument();
32. try
33. {
34. config.Load(dirName);
35. }
36. catch (Exception ex)
37. {
38. throw ex;
39. }
40. XmlNodeList list = config.GetElementsByTagName(tag);
41. return list.Count;
42. }
43. /**//// <summary>
44. ///生成HTML文件
45. /// </summary>
46. /// <param name="configFileName">配置文件的路径名</param>
47. /// <param name="configTag">配置文件中的标签名</param>
48. /// <param name="dir">生成文件所在的文件夹的路径</param>
49. /// <param name="templateFile">模板文件的的路径</param>
50. /// <param name="param">要替换的字符串数组</param>
51. /// <returns>生成的文件名</returns>
52. public void MakeHtml(String configFileName, String configTag, String dir, String templateFile, String[] param)
53. {
54. fileName = null;
55. int count = GetConfig(configFileName, configTag);
56. String[] _replaceStr = new String[count];
57. try
58. {
59. FileStream tFile = File.Open(templateFile, FileMode.Open, FileAccess.Read);
60. StreamReader reader = new StreamReader(tFile, Encoding.GetEncoding("gb2312"));
61. StringBuilder sb = new StringBuilder(reader.ReadToEnd());
62. reader.Close();
63. for (int i = 0; i < count; i++)
64. {
65. sb.Replace("$repalce[" + i + "]$", param[i]);
66. }
67.
68. fileName = DateTime.Now.ToFileTime().ToString() + ".htm";
69.
70. FileStream rFile = File.Create(dir+"/" + fileName);
71. StreamWriter writer = new StreamWriter(rFile, Encoding.GetEncoding("gb2312"));
72. writer.Write(sb.ToString());
73. writer.Flush();
74. writer.Close();
75.
76.
77.
78.
79. }
80. catch (Exception ex)
81. {
82. throw ex;
83. }
84.
85.
86. }
87.
88. public void DeleteHtml(String dirName)
89. {
90. File.Delete(dirName);
91. }
92. }
93.}
94.
95. private int GetConfig(String dirName, String tag) 此方法用于读取配置文件(见后),主要是获得要替换的字符串的个数,在本类同体现为一个字符串数组
96. public void MakeHtml(String configFileName, String configTag, String dir, String templateFile, String[] param) 此方法用于生成静态页面
97.51.52行创建一个字符数组,数组长度为配置文件中的节点个数。55-58行读取模板文件,并用读到的模板文件的HTML代码生成一个StringBuilder对象。59-62行使用StringBuilderd对象的repalce()方法替换标记“$repalce[i]$"为真实的数据
98.64行生成一个唯一的文件名(防止覆盖)66-70行把新的字符串写到文件中。这样就生成了一个静态文件了。
99.下面看一个使用的实例:
100.一个文章管理系统,利用这个类来生成静态页面。
101.首先,建立一个配置文件 config.xml.此文件告诉使用者每个标记的含义。如下
102.<?xml version="1.0" encoding="utf-8" ?>
103.<htmlWeb version="1">
104. <config>
105. <article key="0" value="title"/>
106. <article key="1" value="author"/>
107. <article key="2" value="context"/>
108. <aritcle key="3" value="date"/>
109. </config>
110.</htmlWeb>
111.10这样配置后,类会把标记数组0,1,2,3的位置分别替换为题目,作者,内容,发布日期。
112.看模板文件
113. 1<head>
114. 2<title>模板文件</title>
115. 3</head>
116. 4<body>
117. 5<h1>这是一个简单的HTML页,朋友们可以根据自己的需要重新设计</h1>
118. 6<li>标题:$replace[0]$</li>
119. 7<li>作者:$replace[1]$</li>
120. 8<li>内容:$repalce[2]$</li>
121. 9<li>时间:$repalce[3]$</li>
122.10</body>使用方法:
123. 1using System;
124. 2using System.Data;
125. 3using System.Configuration;
126. 4using System.Web;
127. 5using System.Web.Security;
128. 6using System.Web.UI;
129. 7using System.Web.UI.WebControls;
130. 8using System.Web.UI.WebControls.WebParts;
131. 9using System.Web.UI.HtmlControls;
132.10
133.11namespace UseT
134.12{
135.13 public class Test{
136.14
137.15 public void main(){
138.16 string[] param = new string[4];
139.17 param[0] = "Java教程";
140.18 param[1] = http://www.javaweb.cc; 141.19 param[2] = "这是一个测试文章";
142.20 param[3] = "2009-10-30";
143.21
144.22 htmlWeb.CreateHtm cs = new htmlWeb.CreateHtm();
145.23 cs.MakeHtml("配置文件的路径
146.24“, ”article“, ”生成文件的路径“, "模板文件的路径", param)
147.25
148.26 }
149.27 }
150.28}
151.29只要把相应的参数修改为实际的值,就生成静态文件了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: