本文整理自兩篇相似文章 (ID 67380、67383),針對 ASP.NET 禁用頁面快取的四種常見方法進行去重、深度比較、補充最佳實務與常見誤區說明。
// 在 Page_Load 或 BasePage.OnLoad 中呼叫
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore(); // 關鍵:禁止任何快取儲存
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.AppendHeader("Pragma", "no-cache"); // HTTP/1.0 相容
適用:所有動態頁面、敏感資料頁面、API 端點。
優點:HTTP 標準、控制瀏覽器與 Proxy、程式碼可集中管理。
<head runat="server">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
</head>
缺點:Proxy 忽略、僅影響 HTML 文件本身、HTML5 不建議使用。不可作為唯一依賴。
// 導向時
Response.Redirect("Page.aspx?nocache=" + DateTime.Now.Ticks);
// 或
string url = "Page.aspx?v=" + Guid.NewGuid().ToString("N");
原理:瀏覽器以完整 URL 為快取鍵,參數不同視為新資源。
缺點:URL 汙染、書籤失效、無法防止「上一頁」載入快取、SEO 不友善。僅作輔助。
<script>
function navigateWithoutHistory(url) {
window.location.replace(url); // 當前頁面不留在歷史記錄中
}
</script>
<a href="javascript:navigateWithoutHistory('NextPage.aspx')">下一頁</a>
說明:這**不是禁用快取**,而是防止使用者按「返回鍵」回到前一頁。常用於:登出導向登入頁、付款完成頁、單向流程步驟。需配合方法一使用。
| 方法 | 層級 | 是否真正禁用快取 | 是否防止「上一頁」 | 推薦等級 |
|---|---|---|---|---|
| Response.Cache 標頭 | HTTP 協定 | ✅ 是 (瀏覽器+Proxy) | ❌ 否 (需配合 NoStore) | ⭐⭐⭐⭐⭐ (必須) |
| Meta 標籤 | HTML 文件 | ⚠️ 部分/不可靠 | ❌ 否 | ⭐ (不建議單獨用) |
| 隨機 URL 參數 | 應用層變通 | ❌ 否 (繞過快取機制) | ❌ 否 | ⭐⭐ (輔助用) |
| location.replace | 瀏覽器導向 API | ❌ 否 (不影響快取) | ✅ 是 (替換歷史) | ⭐⭐⭐ (特定情境) |
public class SecurePage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
// 敏感頁面:完全禁用快取
if (this is INeedsNoCache)
{
DisableClientCache(Response);
}
// 一般頁面:允許快取靜態資源,僅禁用頁面 HTML 快取
else
{
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
Response.Cache.SetMaxAge(TimeSpan.Zero);
}
base.OnLoad(e);
}
public static void DisableClientCache(HttpResponse response)
{
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.Cache.SetNoStore();
response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
response.Cache.SetValidUntilExpires(false);
response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
response.AppendHeader("Pragma", "no-cache");
}
}
public interface INeedsNoCache { } // 標記介面,需禁用快取的頁面實作此介面
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" /> <!-- 靜態資源 1 年 -->
</staticContent>
<caching>
<profiles>
<add extension=".aspx" policy="DisableCache" kernelCachePolicy="DisableCache" />
<add extension=".ashx" policy="DisableCache" kernelCachePolicy="DisableCache" />
</profiles>
</caching>
</system.webServer>
總結:ASP.NET 禁用頁面快取**唯一標準有效方法**是伺服器端設定 `Response.Cache` 標頭 (`NoCache` + `NoStore`)。Meta 標籤、隨機參數、location.replace 皆為輔助或不同用途手段。建議建立 `BasePage` 統一管理,依頁面敏感度套用不同快取策略,並搭配 `web.config` 靜態資源長效快取,兼顧安全與效能。