ASP.NET生成静态页面的四种方法

在网上找了几种比较好的生成静态页面的方法,基本上有这几种原理:
1,第一种,直接获得服务器生成的html代码.
图片

    

#region//生成被请求URL静态页面

    public static void getUrltoHtml(string Url, string Path)//Url为动态页面地址,Path为生成的静态页面的物理地址及名称
    {

        try
        {

            System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);

            // Get the response instance.

            System.Net.WebResponse wResp = wReq.GetResponse();

            // Get the response stream.

            System.IO.Stream respStream = wResp.GetResponseStream();

            // Dim reader As StreamReader = New StreamReader(respStream)

            System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("gb2312"));

            string str = reader.ReadToEnd();

            System.IO.StreamWriter sw = new System.IO.StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312"));

            sw.Write(str);

            sw.Flush();

            sw.Close();

           // System.Web.HttpContext.Current.Response.Write(" ");

        }

        catch (System.Exception ex)
        {

            System.Web.HttpContext.Current.Response.Write(ex);

        }

    }

    #endregion
    protected void Button1_Click(object sender, EventArgs e)
    {
        //生成静态页面
        getUrltoHtml("http://localhost:1114/生成静态/way1.aspx", Request.MapPath(".")+"/html/way1.html");
    }

效果如下,原版照搬了aspx的代码,但是不足就是一些aspx的功能无法实现了.
图片
2,第二种方法是从预先做好的模板生成.
图片

Create.cs

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.IO;

using System.Text;

namespace CreatePage
{

    ///

    /// CreatePage的摘要说明。

    ///

    //原理是利用System.IO中的类读写模板文件,然后用Replace替换掉模板中的标签,写入静态html

    // 此类是生成静态网页的小程序

    public class Create
    {

        public void CreatePage()
        {

        }
        /// <summary>
        /// 从模板生成静态页面
        /// </summary>
        /// <param name="strText">标题</param>
        /// <param name="strContent">内容</param>
        /// <param name="strAuthor">作者</param>
        /// <returns>true成功,false失败</returns>
        public static bool WriteFile(string strText, string strContent, string strAuthor)
        {

            string path = HttpContext.Current.Server.MapPath(".") + "/html/";//文件输出目录

            Encoding code = Encoding.GetEncoding("gb2312");

            // 读取模板文件

            string temp = HttpContext.Current.Server.MapPath(".")+"/template/test.html";//模版文件

            StreamReader sr = null;

            StreamWriter sw = null;

            string str = "";

            try
            {

                sr = new StreamReader(temp, code);

                str = sr.ReadToEnd(); // 读取文件

            }

            catch (Exception exp)
            {

                HttpContext.Current.Response.Write(exp.Message);

                HttpContext.Current.Response.End();

                sr.Close();

            }

            string htmlfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";//静态文件名

            // 替换内容

            // 这时,模板文件已经读入到名称为str的变量中了

            str = str.Replace("@ShowArticle", strText); //模板页中的ShowArticle

            str = str.Replace("@biaoti", strText);

            str = str.Replace("@content", strContent);

            str = str.Replace("@author", strAuthor);

            // 写文件

            try
            {

                sw = new StreamWriter(path + htmlfilename, false, code);

                sw.Write(str);

                sw.Flush();

            }

            catch (Exception ex)
            {

                HttpContext.Current.Response.Write(ex.Message);

                HttpContext.Current.Response.End();

            }

            finally
            {

                sw.Close();

            }

            return true;

        }

    }

}



效果如下
图片
第三种方法,把模板放到代码中,既快速又方便.
图片

Create3.cs
using System;

using System.Collections;

using System.Data;

using System.Data.OleDb;

using System.Text;

using System.IO;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;


///

/// 自定义公共函数

///

public class Create3
{

    #region//定义模版页

    public static string SiteTemplate()
    {

        string str = "";//模版页html代码

        str += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
        str += "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>@ShowArticle</title></head>";
        str += "<body><form name=\"form1\" method=\"post\" action=\"way1.aspx\" id=\"form1\"><div><h1>@biaoti</h1><br>作者@author</div><div>@content</div></form></body></html>";
        return str;

    }

    #endregion
    /// <summary>
    /// 根据模板代码生成静态页面
    /// </summary>
    /// <param name="strText">标题</param>
    /// <param name="strContent">内容</param>
    /// <param name="strAuthor">作者</param>
    /// <returns></returns>
    public static bool WriteFile(string strText, string strContent, string strAuthor)
    {

        string path = HttpContext.Current.Server.MapPath(".")+"/html/";//文件输出目录

        Encoding code = Encoding.GetEncoding("gb2312");

        StreamWriter sw = null;

        string str = SiteTemplate();//读取模版页面html代码

        string htmlfilename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";//静态文件名

        // 替换内容

        str = str.Replace("@ShowArticle", strText);

        str = str.Replace("@biaoti", strText);

        str = str.Replace("@content", strContent);

        str = str.Replace("@author", strAuthor);

        // 写文件

        try
        {

            sw = new StreamWriter(path + htmlfilename, false, code);

            sw.Write(str);

            sw.Flush();

        }

        catch (Exception ex)
        {

            HttpContext.Current.Response.Write(ex.Message);

            HttpContext.Current.Response.End();

        }

        finally
        {

            sw.Close();

        }

        return true;

    }

}



效果:
图片

这些都是前三种方法生成的静态页面

图片

第四种方法比较特别,它是让要生成静态的页面继承我们预先定义的一个类,然后他就会自动生成静态页面且访问动态页面会自动转到相应静态页面.并且相应链接都会转换为静态链接.
图片

index.aspx 红色标出的是亮点

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Eshop.Web.Index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>这是第四种生成方法</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>这是第四种生成方法</h1>
        <br />
        
        <html:HtmlPanel ID="hp" runat="server">
            <asp:HyperLink ID="Hy" runat="server" NavigateUrl="~/Index.aspx?page=2">
                   点击
            </asp:HyperLink>
            <br />
            <a href="~/Index.aspx?page=2" runat="server">Hello</a>
        </html:HtmlPanel>
    </div>
    </form>
</body>
</html>

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Eshop.Web.UI;

namespace Eshop.Web
{
    //继承HtmlPage类
    public partial class Index : HtmlPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

      1、路径映射类(UrlMapping),主要对路径进行拆分、拼接。(关键的一步)

      2、过滤流类(FilterStream),主要负责生成静态页面。

      3、静态页面类(HtmlPage),主要是调用UrlMapping和FilterStream类,

          哪个页面想静态化,就继承这个类。

      4、HtmlHandler类,路径后缀为Html的,都由它来处理,与HtmlPage类相似。

      5、HtmlPanel类(控件),页面带上这个控件,超链接会静态化。

FilterStream  保存静态页面

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

namespace Eshop.Web.UI
{
    /// <summary>
    /// 静态网页保存
    /// </summary>
    public class FilterStream : Stream
    {
        private Stream respStream = null;
        private Stream fileStream = null;

        public FilterStream(Stream respStream, string filePath)
        {
            if (respStream == null)
                throw new ArgumentNullException("输出流不能为空");

            this.respStream = respStream;
            
            try
            {
                this.fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);  //写入到文件夹中
            }
            catch { }
        }


        public override bool CanRead
        {
            get { return this.respStream.CanRead; }
        }

        public override bool CanSeek
        {
            get { return this.respStream.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return this.respStream.CanWrite; }
        }

        public override void Flush()
        {
            this.respStream.Flush();

            if (this.fileStream != null)
            {
                this.fileStream.Flush();
            }
        }

        public override long Length
        {
            get { return this.respStream.Length; }
        }

        public override long Position
        {
            get
            {
                return this.respStream.Position;
            }
            set
            {
                this.respStream.Position = value;

                if (this.fileStream != null)
                {
                    this.fileStream.Position = value;
                }
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return this.respStream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            if (this.fileStream != null)
            {
                this.fileStream.Seek(offset, origin);
            }

            return this.respStream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            this.respStream.SetLength(value);

            if (this.fileStream != null)
            {
                this.fileStream.SetLength(value);
            }
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            this.respStream.Write(buffer, offset, count);

            if (this.fileStream != null)
            {
                this.fileStream.Write(buffer, offset, count);
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            this.respStream.Dispose();
            if (this.fileStream != null)
            {
                this.fileStream.Dispose();
            }
        }
    }
}

 HtmlHandler 处理HTML页面
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

namespace Eshop.Web.UI  
{
    /// <summary>
    /// 后缀为HTML的,都经这里处理
    /// web.config
    /// <remove verb="*" path="*.HTML"/>
    /// <add verb="*" path="*.HTML" type="Eshop.Web.UI.HtmlHandler,AspxToHtmlDemo"/>
    /// </summary>
    public class HtmlHandler:IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// 获取物理路径,判断文件夹中有没有存在这个文件
        /// 不存在的话,就会调用FilterStream类进行创建,并写入内容
        /// 存在的话,就直接显示页面
        /// </summary>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

            string htmlPage = request.RawUrl;
            string htmlFile = context.Server.MapPath(htmlPage);

            if (File.Exists(htmlFile))
            {
                response.WriteFile(htmlFile);
                return;
            }

            //Html 文件不存在
            string aspxPage = UrlMapping.HtmlToAspx(htmlPage);
            response.Redirect(aspxPage);
        }

    }
}

HtmlPage
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

namespace Eshop.Web.UI
{
    /// <summary>
    /// 哪个页面想静态化,就继承这个类
    /// </summary>
    public class HtmlPage:Page
    {
        // <summary>
        /// 获取物理路径,判断文件夹中有没有存在这个文件
        /// 不存在的话,就会调用FilterStream类进行创建,并写入内容
        /// 存在的话,就直接显示页面
        /// </summary>
        public override void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;

            string htmlPage = UrlMapping.AspxToHtml(req.RawUrl);
            string htmlFile = context.Server.MapPath(htmlPage);

            if (File.Exists(htmlFile))
            {
                resp.Redirect(htmlPage);
                return;
            }

            // Html 页面不存在
            resp.Filter = new FilterStream(resp.Filter, htmlFile);
            base.ProcessRequest(context);
        }
    }
}

UrlMapping
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

namespace Eshop.Web.UI
{
    /// <summary>
    /// 路径映射
    /// </summary>
    public static class UrlMapping
    {
        //Aspx 转换到 Html
        public static string AspxToHtml(string url)
        {
            //判断路径是否为空
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("路径不能为空");
            }

            //分割路径
            string[] temp = url.Split('?');

            if (temp.Length != 1 && temp.Length != 2)
            {
                throw new ArgumentException(String.Format("路径 {0} 及其参数错误", url));
            }

            //获取路径后缀
            string ext = Path.GetExtension(temp[0]);    
            if (!(ext.Equals(".aspx", StringComparison.OrdinalIgnoreCase)))
            {
                throw new ArgumentException(String.Format("路径 {0} 类型必须为ASPX", url));
            }

            //截取.aspx中前面的内容
            int offset = temp[0].LastIndexOf('.');
            string resource = temp[0].Substring(0, offset);

            //路径不带参数时
            if (temp.Length == 1 || string.IsNullOrEmpty(temp[1]))
            {
                return string.Format("{0}.html", resource);    //拼接
            }

            //路径带参数时
            return string.Format("{0}___{1}.html", resource, temp[1]); //拼接
        }
        
        //Html 转换到 Aspx
        public static string HtmlToAspx(string url)
        {
            //判断路径是否为空
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("路径不能为空");
            }

            string ext = Path.GetExtension(url);
            if (!(ext.Equals(".html", StringComparison.OrdinalIgnoreCase)))
            {
                throw new ArgumentException(String.Format("路径 {0} 类型必须为HTML", url));
            }

            string[] temp = url.Split(new String[] { "___", "." }, StringSplitOptions.RemoveEmptyEntries);
            if (temp.Length == 2)
            {
                return string.Format("{0}.aspx", temp[0]);
            }

            if (temp.Length == 3)
            {
                return String.Format("{0}.aspx?{1}", temp[0], temp[1]);
            }

            throw new ArgumentException(String.Format("资源 {0} 及其参数错误", url));
        }
    }
}


图片
效果
图片
要实现第四种方法分为这么几个步骤:

1,添加Jiangs_AspxToHtml.dll的引用

2,添加web.config配置节sys.web

   

 <system.web>
      <!--以下为生成静态配置节-->
      <globalization requestEncoding="gb2312" responseEncoding="gb2312"/>
      <httpHandlers>
        <remove verb="*" path="*.HTML"/>
        <add verb="*" path="*.HTML" type="Jiangs_AspxToHtml.UI.HtmlHandler"/>
      </httpHandlers>
      <pages>
        <controls>
          <add tagPrefix="html" namespace="Jiangs_AspxToHtml.UI.Controls" assembly="Jiangs_AspxToHtml"/>
        </controls>
      </pages>
      <!--以上为生成静态配置节-->

    </system.web>

3,在要静态化的页面添加using命名空间

using Jiangs_AspxToHtml.UI;

4,页面继承HtmlPage

public partial class JiangsWeb_Default : HtmlPage//继承此类,生成html 

5,打开页面试试生成了没,大功告成!

如果页面内容有改变需要重新生成,只需要删除掉已生成的html页面,它会自动重新生成新的html

6,把Jiangs_AspxToHtml.dll拖到工具栏,有一个HtmlPanel 自定义控件,拖到页面上,然后把body内容放里面,里面的所以连接都会静态化。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值