.net產生靜態頁面原理與代碼

來源:互聯網
上載者:User

一種是直接存取動態網頁面地址,將其產生的html代碼儲存成靜態頁面。另一種是通過讀取頁面模板,對其中需要替換的內容進行替換的方式進行產生。其中前一種方法簡單,對於產生單個頁面或少量頁面比較實用,而對大量的頁面且頁面之間彼此關聯複雜的,第一種就不太方便。對於使用模板的方法稍微複雜,這裡不詳細討論,只給出第一種方法應對不太複雜的項目的應用。

給定產生靜態頁面入口頁面地址,比如index.asp教程x,通過尋找其中以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;")));
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.