現有動態頁面的格式都是類似 pageName.aspx?ID=1的格式,后面由於發布服務器的原因,要求將動態頁面轉為靜態html后上傳。
首先根據頁面生成的格式,枚舉獲取頁面html:
1 foreach (var page in pageList) 2 { 3 string html = ReadHtml(string.Format("pageName.aspx?ID={0}", page.ID)); 4 html = ReplaceListAndSingle(html); 5 WriteHtml(string.Format("pageName_{0}.html", page.ID), html); 6 }
讀取asp.net頁面:
public static string ReadHtml(string sourceurl) { try { System.Net.WebRequest myRequest = System.Net.WebRequest.Create(sourceurl); System.Net.WebResponse myResponse = myRequest.GetResponse(); using (Stream stream = myResponse.GetResponseStream()) { using (StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("utf-8"))) { return sr.ReadToEnd(); } } } catch (Exception ex) { throw new Exception(string.Format("ReadHtml出錯:{0}", ex.Message)); } }
使用正則替換頁面內的動態鏈接:
public static string ReplaceListAndSingle(string html) { html = Regex.Replace(html, @"_list\.aspx\?ID=(\d*)", "_list_$1.html", RegexOptions.IgnoreCase); html = Regex.Replace(html, @"_single\.aspx\?ID=(\d*)", "_single_$1.html", RegexOptions.IgnoreCase); return html.Replace(".aspx", ".html"); }
動態頁面格式為 pageName_list.aspx?ID=1 與 pageName_single.aspx?ID=1,正則替換后變為靜態格式:pageName_list_1.html 與 pageName_single_1.html。
將替換后的頁面html寫入文件:
public static bool WriteHtml(string url, string html) { try { using (StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(url), false, Encoding.GetEncoding("utf-8"))) { sw.WriteLine(html); sw.Close(); } return true; } catch (Exception ex) { throw new Exception(string.Format("WriteHtml出錯:{0}", ex.Message)); } }