$content$) 標示動態區塊。String.Replace 置換標記為實際資料。.htm 檔案,存放於網站目錄。<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>$title$</title>
</head>
<body>
<div>$content$</div>
</body>
</html>
protected void btnGenerate_Click(object sender, EventArgs e)
{
string templatePath = Server.MapPath("~/template.htm");
string outputDir = Server.MapPath("~/static/");
// 確保輸出目錄存在
if (!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir);
string template;
using (var sr = new StreamReader(templatePath, Encoding.UTF8))
template = sr.ReadToEnd();
// 置換
template = template.Replace("$title$", txtTitle.Text);
template = template.Replace("$content$", txtContent.Text);
// 檔名含時間戳避免衝突
string fileName = $"{DateTime.Now:yyyyMMddHHmmss}.htm";
string filePath = Path.Combine(outputDir, fileName);
using (var sw = new StreamWriter(filePath, false, Encoding.UTF8))
sw.Write(template);
// 回應連結
litResult.Text = $"<a href='static/{fileName}' target='_blank'>{fileName}</a> 產生完成";
}
<asp:TextBox ID="txtTitle" runat="server" Width="300" /><br />
<asp:TextBox ID="txtContent" runat="server" TextMode="MultiLine" Rows="10" Width="500" /><br />
<asp:Button ID="btnGenerate" runat="server" Text="產生靜態頁" OnClick="btnGenerate_Click" /><br />
<asp:Literal ID="litResult" runat="server" />
Dictionary 批次 Replace。list_1.htm、list_2.htm,並產生分頁導覽連結。| 優點 | 缺點 |
|---|---|
| 極大降低伺服器 CPU/DB 壓力 | 內容更新需重新產生 (延遲) |
| 利於 SEO、快速載入 | 大量檔案佔用磁碟/Inode |
| 可直接 CDN 快取 | 動態互動功能 (表單、購物車) 需混合模式 |
適用於「讀多寫少」的內容型頁面 (新聞、部落格、商品說明)。高互動頁面採用「靜態化 + AJAX 區塊」混合架構。