雖然現代 Web 架構偏向動態渲染(SSR/CSR),但靜態頁生成在 SEO 型行銷頁、高流量內容頁、離線瀏覽、CDN 快取降低伺服器負載等場景仍具不可替代優勢。核心原理極簡單:讀取模板 → 替換標記 → 輸出檔案。本文提供可直接落地的三大核心方法:ReadHtmlFile、ReturnHtml、writeHtml,並說明分頁靜態化擴充思路。
ReadHtmlFilepublic static string ReadHtmlFile(string templatePath)
{
var code = System.Text.Encoding.GetEncoding("utf-8");
string str = string.Empty;
StreamReader sr = null;
try
{
sr = new StreamReader(HttpContext.Current.Server.MapPath(templatePath), code);
str = sr.ReadToEnd();
}
catch (Exception exp)
{
HttpContext.Current.Response.Write(exp.Message);
HttpContext.Current.Response.End();
}
finally
{
sr?.Dispose();
sr?.Close();
}
return str;
}
ReturnHtmlpublic static string ReturnHtml(string html)
{
string newHtml = html;
newHtml = newHtml.Replace("<#Title#>", "這個是標題替換");
// newHtml = newHtml.Replace("<#Content#>", "這個是內容替換");
newHtml = CreateList(newHtml); // 若有列表區塊可擴充
return newHtml;
}
// 範例:列表區塊循環替換(略)
private static string CreateList(string html) { /* ... */ return html; }
writeHtmlpublic static void writeHtml(string fileName, string html)
{
var code = System.Text.Encoding.GetEncoding("utf-8");
string fullPath = HttpContext.Current.Server.MapPath(fileName);
StreamWriter sw = null;
try
{
sw = new StreamWriter(fullPath, false, code);
sw.Write(html);
sw.Flush();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw?.Close();
}
}
// 1. 讀取模板
string template = ReadHtmlFile("~/Templates/ArticleTemplate.html");
// 2. 替換標記(實際專案中從 DB 取得資料)
string html = ReturnHtml(template);
// 3. 輸出靜態檔
writeHtml("~/StaticPages/article_123.html", html);
<!DOCTYPE html>
<html>
<head><title><#Title#></title></head>
<body>
<h1><#Title#></h1>
<div><#Content#></div>
<ul><#List#></ul>
</body>
</html>
若列表頁需分頁,邏輯為:查詢總筆數 → 計算總頁數 → 迴圈每頁呼叫上述三步驟 → 產生 page_1.html、page_2.html ...。建議搭配背景工作(Hangfire/Quartz)非同步生成,避免阻塞 Web 執行緒。
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 模板替換法 (本文) | 零依賴、部署簡單、完全控制輸出 | 手工維護標記、無型別安全、複雜邏輯難維護 | 舊專案維護、簡單行銷頁、離線封存 |
| RazorEngine / RazorLight | 強型別模板、支援邏輯/迴圈/部分視圖、效能佳 | 需引入套件、學習曲線稍高 | 新專案、需維護大量模板 |
| SSG (Next.js, Astro, Hugo) | 生態豐富、支援增量建置、自動最佳化 | 技術棧切換成本高 | 全新專案、內容導向站點 |
Server.MapPath 僅在 HttpContext 存在時可用;背景工作需自行解析實體路徑。HtmlEncode。模板替換法是靜態頁生成的「Hello World」,理解其本質後,您可以根據專案規模選擇繼續深化(導入 RazorEngine)、或轉型現代 SSG 架構。無論技術如何演進,「資料 + 模板 = 靜態頁」的核心思想永遠不變。