gk-auto 发表于 2021-8-22 13:29:48

ASP.NET 动态生成html文件, 如何生成静态页面

1. 使用场景

适用于服务器功能不强的web站点,不希望频繁通过读取数据库来展示内容,当有新的内容产生时,生成静态页面存放内容,数据库中只保留如标题,类别等一些查询关键字。


2. 使用静态页面的好处
(1)提高网站的访问速度
(2)减轻服务器负担
(3)利于搜索引擎抓取


3. ASP.NET生成静态页面的思路
(1)创建模板template.html文件,在里面定义一些特殊的字符串格式用于替换内容,如$htmlformat
(2)读取模板内容到指定对象中
(3)将特殊的字符串格式替换为你想要的内容
(4)创建新的静态页面,并将替换完标签的内容写入到文件中即可

4.实现

定义html模板文件"template.html",注意标签里内容


<!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=utf-8" />
    <title></title>
</head>

<body>
    <!--标题-->
    <div>$htmlformat</div>
    <!--内容-->
    <div>$htmlformat</div>
</body>
</html>

C#生成代码

protected void Button1_Click(object sender, EventArgs e)
{
    // 01.读取html模板
    string template = "";
    try
    {
      using (StreamReader sr = new StreamReader(Server.MapPath("template.html")))
      {
            template = sr.ReadToEnd();
      }
    }
    catch (Exception ex)
    {
      Response.Write(ex.Message);
      Response.Write("<script>alert('读取文件错误.')</script>");
    }

    // 02.定义和html标记数目一致的数组并赋值
    string[] format = new string;
    format = "这里是标题";
    format = "这里是内容";

    // 03.替换html模板里的标签为实际想要的值
    for (int i = 0; i < 4; i++)
    {
      template = template.Replace("$htmlformat[" + i + "]", format);
    }

    // 04.生成html文件
    try
    {
      using (StreamWriter sw = new StreamWriter(Server.MapPath("output.html"), false, Encoding.UTF8))
      {
            sw.WriteLine(template);
      }

      Response.Write("<script>alert('已生成html文件.')</script>");
    }
    catch
    {
      Response.Write("生成html文件失败.");
    }
}

吴彦乔 发表于 2021-8-22 13:29:48

加油,加油,不要沉下去,我是最热贴

zengqing 发表于 2021-8-22 13:38:58

这个类目最活跃了!赞一个!

qijunx 发表于 2025-11-20 07:49:49

路过打卡,为优质内容疯狂打 call

暗号暗号 发表于 2025-11-20 07:55:09

说得对!狠狠赞同,没毛病~

zjc 发表于 2025-11-20 07:57:26

理性围观,感觉大家说得都有道理

刘道垒 发表于 2025-11-20 07:57:42

原来还有这种操作,长见识了!

zhulong 发表于 2025-11-20 07:58:09

水贴也要有仪式感,我先来打卡~

邓日龙_R78NP 发表于 2025-11-20 07:58:31

谁懂啊!这内容我能循环看十遍

xuhailin1185 发表于 2025-11-20 07:59:46

画面感太强了,仿佛身临其境!
页: [1] 2
查看完整版本: ASP.NET 动态生成html文件, 如何生成静态页面