部署新版 CSS 時,瀏覽器常因快取舊檔案導致版面錯亂。傳統解法需手動修改 `` 版本號,極易遺漏。本文實作一個 伺服器端自訂控制項,自動偵測 CSS 檔案最後修改時間並附加查詢字串,徹底解決快取問題。
<CWeb:CSSInclude ID="CSSInclude1" runat="server"
EnableViewState="false"
HRef="~/css/base.css"
Rel="stylesheet"
Type="text/css"
CacheKey="BaseCSS" />
HRef:CSS 檔案相對/虛擬路徑。Rel、Type:對應 `` 標籤屬性。CacheKey:快取索引鍵名稱(必填),用於儲存版本戳記。private string GetIncludeUrlWithVersion()
{
string url = string.Empty;
string version = "1";
if (string.IsNullOrEmpty(CacheKey))
throw new ArgumentException("CacheKey 不可為空。");
if (Page.Cache[CacheKey] == null)
{
FileInfo fileInfo = new FileInfo(Page.Server.MapPath(HRef));
if (fileInfo.Exists)
{
version = fileInfo.LastWriteTime.ToString("ddMMyyyyhhmmss");
CacheDependency dep = new CacheDependency(fileInfo.FullName);
Page.Cache.Insert(CacheKey, version, dep);
}
}
else
{
version = Page.Cache[CacheKey] as string;
}
return ResolveUrl(HRef) + "?v=" + version;
}
LastWriteTime 產生版本字串(精確到秒),存入 `Cache` 並建立 `CacheDependency` 監聽檔案變更。同樣邏輯可封裝為 `JSInclude` 控制項,解決 `.js` 快取問題。此外,配合 IIS `OutputCache`、自訂 HTTP 標頭 (`Cache-Control: max-age=31536000, immutable`) 可進一步優化靜態資源快取策略。