首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET OutputCache 頁面輸出快取完整指南:屬性詳解與實戰策略

     編輯:ASP.NET 基礎

OutputCache 核心機制

頁面輸出快取將完整渲染後的 HTML 直接存入伺服器記憶體,後續請求繞過頁面生命週期直接回應,大幅降低 CPU 與資料庫負載。適用於「資料量大、互動少、內容相對靜態」的頁面(如商品列表、新聞詳情、報表展示)。

@OutputCache 指令十大屬性詳細說明

屬性說明常用值/範例
Duration快存秒數(必填)Duration="120" 緩存 2 分鐘
VaryByParam依查詢字串/表單參數變化快取(必填)VaryByParam="id"、VaryByParam="*" (全部)、VaryByParam="none" (不變化)
VaryByHeader依 HTTP Header 變化快取VaryByHeader="User-Agent" 區分裝置
VaryByCustom自定義變化邏輯(需覆寫 Global.asax GetVaryByCustomString)VaryByCustom="browser" 依瀏覽器類型
Location快取儲存位置Any(預設) | Client | Server | None | ServerAndClient | Downstream
CacheProfile引用 web.config 定義的快取設定檔CacheProfile="LongCache"
NoStore發送 Cache-Control: no-storeNoStore="true" 防止敏感頁面被快取
VaryByControl依使用者控制項屬性變化快取VaryByControl="ddlCategory"
Enabled啟用/停用快取Enabled="false" 動態關閉
SqlDependencySQL 快取依賴字串SqlDependency="CommandNotification"

實戰配置範例

基礎:全頁快取 2 分鐘

<%@ OutputCache Duration="120" VaryByParam="none" %>

進階:依商品 ID 区分快取

<%@ OutputCache Duration="120" VaryByParam="id" %>

Product.aspx?id=1 與 id=100 將擁有獨立快取副本。

多參數組合

<%@ OutputCache Duration="300" VaryByParam="category;page;sort" %>

依瀏覽器類型區分(行動版/桌面版)

<%@ OutputCache Duration="120" VaryByParam="none" VaryByCustom="browser" %>

需在 Global.asax 實作:

public override string GetVaryByCustomString(HttpContext context, string custom) {
    if (custom == "browser") return context.Request.Browser.Type; // 如 "Chrome98", "MobileSafari"
    return base.GetVaryByCustomString(context, custom);
}

Web.config 集中管理快取設定檔

<system.web>
  <caching>
    <outputCacheSettings>
      <outputCacheProfiles>
        <add name="LongCache" duration="3600" varyByParam="id" location="Server" />
        <add name="ShortCache" duration="60" varyByParam="*" location="Any" />
      </outputCacheProfiles>
    </outputCacheSettings>
  </caching>
</system.web>

頁面引用:<%@ OutputCache CacheProfile="LongCache" %>

常見陷阱與解決方案

問題原因解決
使用者看到舊資料Duration 過長、未正確設定 VaryByParam縮短 Duration、加入關鍵參數、或改用資料快取 + 片段快取
登入後仍看到登入前頁面Location="Client" 或 Proxy 快取設定 Location="Server"、NoStore="true"、或動態關閉快取
Postback 失效OutputCache 繞過頁面生命週期,事件不觸發互動頁面勿用整頁快取,改用 <%@ OutputCache ... %> 於 UserControl (片段快取)
記憶體暴增VaryByParam="*" 產生大量變體精確指定參數、設定 location="Server" 並監控記憶體

片段快取:UserControl 級別的彈性

<%@ Control Language="C#" %>
<%@ OutputCache Duration="60" VaryByParam="categoryId" %>
<asp:Repeater ID="rptProducts" runat="server">...</asp:Repeater>

主頁面不快取,僅快取商品列表區塊,兼顧動態與效能。

總結

OutputCache 是 ASP.NET 效能優化的第一道防線。掌握 Duration + VaryByParam 核心組合,善用 CacheProfile 集中管理,結合 片段快取 處理局部動態內容,即可在最小代碼改動下獲得數倍吞吐量提升。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved