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

转自:http://www.cnblogs.com/PFly/p/4414342.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)); }
        }
复制代码

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值