ASP.NET 根据现有动态页面生成静态Html
现有动态页面的格式都是类似 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)); } }