public void DisableClientCache()
{
// 1. 禁止緩存
Response.Buffer = true; // 啟用緩衝
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); // 過期時間設為過去
Response.Cache.SetExpires(DateTime.Now.AddDays(-1)); // HTTP 1.1 標準過期頭
Response.Expires = 0; // HTTP 1.0 兼容
Response.CacheControl = "no-cache"; // HTTP 1.0 緩存控制
// 2. 更完整的 HTTP 1.1 標準頭(推薦補充)
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore(); // 禁止存儲任何版本
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0 兼容
}
| 屬性/方法 | HTTP 標頭 | 協議版本 | 作用 |
|---|---|---|---|
| ExpiresAbsolute | Expires | HTTP 1.0 | 指定過期絕對時間 |
| Cache.SetExpires | Expires | HTTP 1.1 | 標準過期時間 |
| Expires = 0 | Expires | HTTP 1.0 | 立即過期 |
| CacheControl | Cache-Control | HTTP 1.0 | no-cache 要求驗證 |
| SetCacheability | Cache-Control | HTTP 1.1 | NoCache/Private/Public |
| SetNoStore | Cache-Control: no-store | HTTP 1.1 | 絕對禁止緩存 |
<%@ Page Language="C#" %> <%@ OutputCache Duration="1" VaryByParam="None" Location="None" NoStore="true" %>
或在 web.config 全局配置:
<%@ OutputCache CacheProfile="NoCache" %>
protected void Page_Load(object sender, EventArgs e)
{
// 1. 核心防緩存頭
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
// 2. 兼容性頭
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");
// 3. 安全相關頭(防敏感信息泄露)
Response.AppendHeader("X-Content-Type-Options", "nosniff");
Response.AppendHeader("X-Frame-Options", "DENY");
// 正常業務邏輯...
}
Response.Clear();
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.Private); // 僅私有緩存
Response.Cache.SetMaxAge(TimeSpan.Zero);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=report.pdf");
Response.BinaryWrite(fileBytes);
Response.End();
Response.ContentType = "application/json"; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); // 返回 JSON 數據...
public class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
// 控制器/Action 標記
[NoCache]
public ActionResult SensitiveData() { ... }
Cache-Control: no-cache, no-store, must-revalidatePragma: no-cache、Expires: -1 或過去時間Cache-Control: private精準控制緩存策略,平衡性能與數據安全,是 Web 應用工程化的必修課。