在高流量的 Web 應用中,將動態內容預先渲染為靜態 HTML 檔案,能大幅降低伺服器負載、提升回應速度,並有利於 SEO。本文展示一個完整的 ASP.NET (C#) 實作範例,涵蓋資料存取、HTML 模板組裝、目錄管理與檔案寫入。
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.UI;
namespace BankAccount.test
{
public class HtmlWriter : Page
{
private SqlDataAdapter _adapter;
private SqlConnection _conn;
private DataTable _dt;
private readonly string _connStr = System.Configuration.ConfigurationSettings.AppSettings["cns"];
private void Page_Load(object sender, EventArgs e)
{
try
{
// 1. 取得動態資料
string sql = "SELECT Cmp_description FROM Company WHERE Cmp_number = '123567'";
string description = "";
_dt = new DataTable();
_conn = new SqlConnection(_connStr);
_conn.Open();
_adapter = new SqlDataAdapter(sql, _conn);
_adapter.Fill(_dt);
if (_dt.Rows.Count > 0)
description = _dt.Rows[0]["Cmp_description"].ToString();
// 2. 組裝 HTML 內容
string title = "動態生成的靜態頁面";
string html = $@"
{title}
{title}
{description}
";
// 3. 依年月建立目錄結構
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
string basePath = Server.MapPath(@"\BankAccount\test\");
string monthDir = DateTime.Now.ToString("yyyyMM");
string savePath = Path.Combine(basePath, monthDir);
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
// 4. 寫入檔案
string fullPath = Path.Combine(savePath, fileName);
CreateHtmlFile(fullPath, html);
// 5. 前端提示
ClientScript.RegisterStartupScript(GetType(), "",
"");
}
catch (IOException ex)
{
// 建議記錄日誌而非直接拋出
throw new ApplicationException("生成靜態頁面失敗", ex);
}
finally
{
_conn?.Close();
}
}
private void CreateHtmlFile(string path, string content)
{
using (FileStream fs = new FileStream(path, FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8))
{
sw.Write(content);
}
}
}
}
Server.MapPath 將虛擬路徑轉為實體路徑yyyyMM 格式建立年月分層目錄,避免單一目錄檔案過多影響效能Directory.Exists + CreateDirectory 確保目錄存在$@"") 提升可讀性,實際專案建議使用 Razor 模板或 StringBuildercharset=utf-8 確保中文正常顯示using 區塊自動釋放 FileStream/StreamWriterfinally 區塊確保資料庫連線關閉Task.Run 或背景工作服務 (Hangfire/Quartz) 避免阻塞請求執行緒
[HTTP 請求]
↓
[Page_Load] → 讀取 DB → 組裝 HTML 字串
↓
[建立年月目錄] → [寫入 .html 檔案]
↓
[回傳 JavaScript Alert 提示完成]
動態生成靜態頁面是經典的效能優化手法。現代架構下,更常見的是結合「靜態站點生成器 (SSG)」、「增量式靜態再生 (ISR)」或「邊緣渲染」。但理解伺服器端直接寫檔的基本原理,對於維護舊系統、或在無法使用新框架的環境中實作快取策略,仍具備實務價值。