[C#][ASP.NET MVC]Output Caching
針對相同資料的網頁內容,如果網站使用Cache可以改善一定的效能,
因為可以避免任何的Client端每一次的請求都去資料庫查詢(可直接從Cache取得),進而降低DB Server負擔,
而在MVC中只要簡單的透過Action Filters的OutputCache屬性就可輕易達到Cache效果,使用OutputCache時,
預設情況下Location屬性的值是Any,內容被Cache在三個地方:Web服務器、代理服務器和瀏覽器。
可以通過修改 OutputCache attribute的Location去控制內容Cache的地方。
Location的值清單:
- Any
 - Client
 - Downstream
 - Server
 - None
 - ServerAndClient
 
自己大概實作紀錄一下。
Add OutputCache(30秒) in Controller
 [OutputCache( Duration = 30, VaryByParam = "None" )]
        public ActionResult Index()
        {
            ViewData[ "Message" ] = "現在時間:"+DateTime.Now.ToLocalTime();
            return View();
        }
因為整個View都受到Cached影響,導致30秒後更新View才能看到時間的變化,
但假設我們不要Cached整個View呢?這時就要自己來擴展Html helper了,
而Haccked也提供了substitution control source code,
substitution process大概如下
Source code
public delegate String MvcCacheCallback( HttpContextBase context );
        public static object Substitute( this HtmlHelper html, MvcCacheCallback cb )
        {
            html.ViewContext.HttpContext.Response.WriteSubstitution(
                c => HttpUtility.HtmlEncode(
                    cb( new HttpContextWrapper( c ) )
                ) );
            return null;
        }
Controller
[OutputCache( Duration = 60, VaryByParam = "None" )]
        public ActionResult Index()
        {
            ViewData[ "Message" ] = "現在時間:"+DateTime.Now.ToLocalTime();
            return View();            
        }
View
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
    <%--  this is cached--%>
    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
    <!-- and this is not -->
    <%= Html.Substitute(c => DateTime.Now.ToString()) %>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>
</asp:Content>
可以看到只有紅色框被Cached(Controller to View),而下面區塊時間在更新View後依然可以正常取得當前時間。
關於Output Caching更詳細內容可以參考 Improving Performance with Output Caching (C#)。
參考