asp.net批量生成静态网页

眉间皱痕 提交于 2020-03-22 08:50:38

做了那么久的动态网页,特别是类似于文章或者是新闻系统,都是按照很传统的方法来做的。但是看到越来越多的网站都使用生成静态网页的方法,于是我也打算使用这个方法实践一下。希望对一些有这方面的需要的朋友提供点帮助。

 

本人使用IIS6.0+asp.net 2.0制作,并测试成功。

 

实现效果图:

生成文章以后的页面:

我在输入框里输入了生成ID号从110的文章,通过查询数据库得出结果并批量生成静态页面,然后返回根据刚才生成的页面的内容生成了主页index.html。

点击第三个文章,然后进入到查看文章详细内容的页面:

这是我用的是我们公司的网页做模板生成的式样(本文示例并不是这样的,要更好看的样式,请自行设计模板。)

 

以下是我的实践过程:

首先制作要生成HTML页面的模板:

<!-- temp.htm -->

<html>

<head>

<title> $htmlformat[0]</title>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<!-- 式样表自己制作 -->

</head>

<body>

<table>

<tr><!--文章导航 -->

        <td algin=right> $htmlformat[4]</td>

</tr>

 

    <tr><!--文章的标题 -->

        <td algin=center> $htmlformat[0]</td>

</tr>

<tr><!--发表时间 -->

        <td algin=right> $htmlformat[1]</td>

</tr>

<tr><!--文章概述 -->

        <td algin=right> $htmlformat[2]</td>

</tr>

<tr><!--文章内容 -->

        <td algin=right> $htmlformat[3]</td>

</tr>

</table>

</body>

</html>

<!--index_tmp.htm -->

<!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>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<title>Index</title>

</head>

<body>

$htmlformat[0]

</body>

</html>

 

模板完成后,接下来就是根据文章的ID从数据库中读出相关的内容了。

我的数据库设计如下:

Article

Articles_id 文章id

Article 文章内容

Title 标题

Articledatetime 添加时间

Articlesgroup_parent_id 父栏目编号

Articledescription 文章概述

 

Articlesgroup

Articlesgroup_id 栏目ID

Groupname 栏目名称

Articlesgroup_parent_id 父栏目ID

Groupdescription 概述

 

<!—CreateHTML.aspx -->

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateHTML.aspx.cs" Inherits="CreateHTML" %>

 

<!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>

        要生成的文章ID号:<br />

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>

    </form>

</body>

</html>

 

 

<!—CreateHTML.aspx.cs -->

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

using System.Text;

 

public partial class CreateHTML : System.Web.UI.Page

{

    public string title = "", content = "", datetime = "", desc = "", pages = "", nowPosition = "", positionlist = null, forindex = "";

 

    protected void Page_Load(object sender, EventArgs e)

    {

       

    }

 

    //获取文章内容

    private void GetArticle(string articles_id)

    {

        SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=city;database=test;");

        string sql = "select * from articles where articles_id=" + articles_id;

        SqlCommand cmd = new SqlCommand(sql, conn);

        conn.Open();

        SqlDataReader sdr = cmd.ExecuteReader();

        if (sdr.Read())

        {

            nowPosition = this.GetPosition(sdr["articlesgroup_parent_id"].ToString(), positionlist);

            title = sdr["title"].ToString();

            content = Server.HtmlDecode(sdr["article"].ToString());

            desc = sdr["articledescription"].ToString();

            datetime = sdr["articledatetime"].ToString();

            forindex += "<a href='article" + articles_id + ".html'>" + sdr["title"] + "</a><br />";

        }

        else

        {

            title = "";

            content = "";

            desc = "";

            datetime = "";

        }

        conn.Close();

    }

 

    //创建文章HTML

    private void Createhtml(string article_id)

    {

        this.GetArticle(article_id);

        if (title != "" && content != "")

        {//防止生成空数据的页面

            string[] format = new string[5];//定义和htmlyem标记数目一致的数组

            StringBuilder htmltext = new StringBuilder();

            try

            {

                using (StreamReader sr = new StreamReader(Server.MapPath("temp.htm")))

                {

                    String line;

                    while ((line = sr.ReadLine()) != null)

                    {

                        htmltext.Append(line);

                    }

                    sr.Close();

                }

            }

            catch

            {

                Response.Write("<Script>alert('读取文件错误')</Script>");

            }

 

////---------------------给标记数组赋值------------  

            format[0] = title;

            format[1] = datetime;

            format[2] = desc;

            format[3] = content;

            format[4] = nowPosition;

            ////----------替换htm里的标记为你想加的内容

            for (int i = 0; i < 5; i++)

            {

                htmltext.Replace("$htmlformat[" + i + "]", format[i]);

            }

            //----------生成htm文件------------------――   

            try

            {

                using (StreamWriter sw = new StreamWriter(Server.MapPath("html/article" + article_id + ".html"), false, System.Text.Encoding.GetEncoding("GB2312")))

                {

                    sw.WriteLine(htmltext);

                    sw.Flush();

                    sw.Close();

                }

            }

            catch

            {

                Response.Write("The file could not be wirte:");

            }

        }

    }

    #region 得到现在的位置(无限级栏目)

    public string GetPosition(string articlesgroup_id, string positionlist)

    {

        string articlesgroup_parent_id = "";

        string groupname = "";

 

        string NowPosition = "";

        if (articlesgroup_id == "")

            articlesgroup_id = "0";

        string sql = "select articlesgroup_parent_id, groupname from articlesgroup where articlesgroup_id = " + articlesgroup_id + "";

        SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=city;database=test;");

        SqlCommand cmd = new SqlCommand(sql, conn);

        cmd.CommandType = CommandType.Text;

        try

        {

            conn.Open();

            SqlDataReader sdr;

            sdr = cmd.ExecuteReader();

            if (!sdr.Read())

            {

                NowPosition = "Current Location:<a href=categorylist.aspx>Base</a>";

            }

            else

            {

                articlesgroup_parent_id = sdr["articlesgroup_parent_id"].ToString();

                groupname = sdr["groupname"].ToString();

                if (groupname != "")

                    NowPosition = GetPosition(articlesgroup_parent_id, groupname);

            }

            sdr.Close();

            conn.Close();

            if (articlesgroup_id != "0")

                NowPosition = NowPosition + " -> <a href=categorylist.aspx?viewcatagorie_id=" + articlesgroup_id + ">" + groupname + "</a>";

        }

        catch { }

        return NowPosition;

    }

    #endregion

 

protected void Button1_Click(object sender, EventArgs e)

    {

        for(int i=Convert.ToInt32(this.TextBox1.Text);i<=Convert.ToInt32(this.TextBox2.Text);i++)

            this.Createhtml(i.ToString());

        string[] format = new string[1];//定义和htmlyem标记数目一致的数组

        StringBuilder htmltext = new StringBuilder();

        try

        {

            using (StreamReader sr = new StreamReader(Server.MapPath("index_tmp.htm")))

            {

                String line;

                while ((line = sr.ReadLine()) != null)

                {

                    htmltext.Append(line);

                }

                sr.Close();

            }

        }

        catch

        {

            Response.Write("<Script>alert('读取文件错误')</Script>");

        }

        ////---------------------给标记数组赋值------------  

        format[0] = forindex;

        ////----------替换htm里的标记为你想加的内容

        htmltext.Replace("$htmlformat[0]", format[0]);

        //----------生成htm文件------------------――   

        try

        {

            using (StreamWriter sw = new StreamWriter(Server.MapPath("index.html"), false, System.Text.Encoding.GetEncoding("GB2312")))

            {

                sw.WriteLine(htmltext);

                sw.Flush();

                sw.Close();

            }

        }

        catch

        {

            Response.Write("The file could not be wirte:");

        }

 

        Response.Redirect("index.html");

    }

}

本程序生成页面的速度很快,生成800个页面只需要4秒钟左右。但是方法不是很好,代码还不够简明,希望广大朋友们提出意见。如果你对这方法有什么改进的办法,也不妨拿出来大家分享一下。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!