ASP.NET WebForms 換膚 (Theme/Skin) 雖有內建機制,但靈活度有限。本文介紹一種輕量、通用的換膚技巧:**在基底頁面 `BasePage` 覆寫 `Render` 方法,攔截 HTML 輸出流,於 `` 前動態插入主題 CSS ``**,無需修改每個頁面、無需 `PlaceHolder`、相容 `UpdatePanel` 非同步回發。
public class BasePage : System.Web.UI.Page {
protected override void Render(HtmlTextWriter writer) {
using (var sw = new StringWriter())
using (var hw = new HtmlTextWriter(sw)) {
base.Render(hw); // 讓頁面正常渲染至 StringWriter
string html = sw.ToString();
// 取得當前使用者主題 (Session/Profile/Cookie/DB)
string theme = GetCurrentTheme(); // 如 "dark", "blue", "high-contrast"
string cssLink = $"";
// 插入 之前
int headEnd = html.LastIndexOf("", StringComparison.OrdinalIgnoreCase);
if (headEnd >= 0) {
html = html.Insert(headEnd, cssLink);
}
writer.Write(html);
}
}
private string GetCurrentTheme() {
// 優先順序:QueryString > Cookie > Session > Profile > Default
return Request.QueryString["theme"]
?? Request.Cookies["UI_Theme"]?.Value
?? Session["Theme"]?.ToString()
?? "default";
}
}
public partial class Default : BasePage { ... }
public partial class ArticleDetail : BasePage { ... }
// ThemeSwitcher.ashx 或 PageMethod
[WebMethod]
public static void SetTheme(string theme) {
HttpContext.Current.Session["Theme"] = theme;
var cookie = new HttpCookie("UI_Theme", theme) { Expires = DateTime.Now.AddYears(1), Path = "/" };
HttpContext.Current.Response.Cookies.Set(cookie);
}
// 前端呼叫
fetch('/ThemeSwitcher.ashx?theme=dark', {method:'POST', credentials:'include'})
.then(() => location.reload()); // 重載套用新 CSS
| 優點 | 缺點/注意 |
|---|---|
| 零侵入:既有頁面無需修改 | 字串操作 HTML,極大頁面可能影響效能 (建議啟用 OutputCache) |
| 支援動態主題 (登入後才定) | 若頁面已有 `` 可能產生重複,需在插入前移除舊主題 link |
| 相容 UpdatePanel 非同步回發 | 非同步回發不會重新執行 Render,主題切換需全頁重載或改用 JS 切換 link.href |
| 可結合 CSP nonce 動態產生 | 需注意 HTML 編碼防 XSS (主題名稱應白名單驗證) |
// 在 Insert 前先移除既有主題 link
var regex = new Regex(@"]+href=[""']?[^"">]*\/themes\/[^"">]*\.css[^>]*>", RegexOptions.IgnoreCase);
html = regex.Replace(html, "");
// 再插入新主題
| 方案 | 優點 | 缺點 |
|---|---|---|
| WebForms Theme/Skin | 內建、設計時支援 | 僅控制伺服器控制項屬性、無法換 CSS 檔案、靈活度低 |
| CSS Custom Properties (CSS Variables) | 單一 CSS、JS 切換極快、無需重載 | IE 不支援、需重構樣式表 |
| Render 注入 (本文) | 相容舊專案、零改動頁面、支援任意 CSS | 字串處理開銷、全頁重載 |
| HttpModule 注入 | 全站生效、無需基底頁面 | 同樣字串處理、需小心處理非 HTML 回應 (JSON、圖片) |
對於維護中的 WebForms 專案,`BasePage.Render` 注入法是以最小代價實現動態換膚的最佳平衡點;新專案建議直接採用 CSS Variables + JS 切換。