webearly

导航

利用ASP.NET生成静态页面

  目前生成静态页面的方法大致分为两种,一种是直接访问动态页面地址,将其生成的html代码保存成静态页面。另一种是通过读取页面模板,对其中需要替换的内容进行替换的方式进行生成。其中前一种方法简单,对于生成单个页面或少量页面比较实用,而对大量的页面且页面之间彼此关联复杂的,第一种就不太方便。对于使用模板的方法稍微复杂,这里不详细讨论,只给出第一种方法应对不太复杂的项目的应用。

  给定生成静态页面入口页面地址,比如Index.aspx,通过查找其中以href=开始的链接的页面地址,对其按一定规则进行替换后,生成静态化之后的Index.html,再依次对Index.aspx中的所有链接页面依次进行静态化,如此循环。

  下面的示例代码演示了如何将页面中的动态链接地址替换成按规则命名的静态地址。

以下是代码片段:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace WebTest
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string content = "<a target=\"_blank\" href=\"Product.aspx?classId=123\"><a target=\"_blank\" href=\"Product-view.aspx\"><a target=\"_blank\" href=\"Product-view.aspx?id=59\"><a target=\"_blank\" href=\"Product-view.aspx?id=11159\">";
string newContent = content;
Regex rg = new Regex("href="); //正则定位到链接
int len = 5; //正则字符长度
MatchCollection mc = rg.Matches(content);
foreach (Match m in mc)
{
int startIndex = m.Index + len + 1; //定位到的URL的起始位置
int endIndex = content.IndexOf("\"", m.Index + len + 1); //定位到的URL的结束位置
string originalURL = content.Substring(startIndex, endIndex - startIndex); //获取到URL的全地址
string newURL = "";
newURL = originalURL.Replace(".aspx?classId=", "-class-"); //产品类型的替换
newURL = newURL.Replace(".aspx?id=", "-"); //产品的替换
newURL = newURL.Replace(".aspx", "");
newURL += ".html";

newContent = newContent.Replace(originalURL +"\"", newURL +"\""); //替换掉原URL地址为静态地址
}

Response.Write(string.Format("原内容:{0}<br/>新内容:{1}", content.Replace("<", "&lt;").Replace(">", "&gt;"), newContent.Replace("<", "&lt;").Replace(">", "&gt;")));
}
}
}
 

   该页面运行效果结果如下:

以下是代码片段: 
原内容:<a target="_blank" href="Product.aspx?classId=123"> <a target="_blank" href="Product-view.aspx"> <a target="_blank" href="Product-view.aspx?id=59"> <a target="_blank" href="Product-view.aspx?id=11159">
新内容:<a target="_blank" href="Product-class-123.html"> <a target="_blank" href="Product-view.html"> <a target="_blank" href="Product-view-59.html"> <a target="_blank" href="Product-view-11159.html">

posted on 2011-03-26 13:16  early  阅读(446)  评论(0编辑  收藏  举报