根据现有动态页面生成静态Html

王朝学院·作者佚名  2016-05-21
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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)); } }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航