- 打卡等级:即来则安
- 打卡总天数:27
- 打卡月天数:6
- 打卡总奖励:7736
- 最近打卡:2025-12-20 00:35:11
管理员
- 积分
- 23881
|
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[0]</div>
<!--内容-->
<div>$htmlformat[1]</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[4];
format[0] = "这里是标题";
format[1] = "这里是内容";
// 03.替换html模板里的标签为实际想要的值
for (int i = 0; i < 4; i++)
{
template = template.Replace("$htmlformat[" + i + "]", format[i]);
}
// 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文件失败.");
}
}
|
|