2007年11月13日 星期二

ASP.NET Cache 機制

在很多情況下, aspx cache 是很有用的.
而且 IIS 的 aspx cache 是不需要寫  code 的. (除非你的 aspx 太過複雜, 過份使用 Session 等等)

先參考官方文件:

http://msdn2.microsoft.com/zh-tw/library/hdxfb6cy(vs.80).aspx

很簡單, 對於一段時間內固定的 aspx, 在 aspx 前面加上

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

這樣就可以囉...
當然, 大部分的情況下, VaryByParam 是重點, aspx 如果要有不同的 input 產出不同的 output.
VaryByParam 就是指明哪些是 Get/Post 的參數屬於 input. 用來做為 cache hit key.


可惜 ASP.NET 2.0 的 __VIEWSTATE 會隨著時間變化,
所以使用 VaryByParam="*" 在大多數的 aspx 網頁廢掉了...


至於 VaryByCustom 是進階用法, 需要搭配寫 code 在 Global.asax.cs 當中,
範例:


        public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (String.Compare
(arg,
"sessionid", StringComparison.InvariantCultureIgnoreCase) == 0)
{
HttpCookie cookie = context.Request.Cookies["ASP.NET_SessionId"];
if (cookie != null)
return cookie.Value;
}
return base.GetVaryByCustomString(context, arg);
}
 

然後就可以用
<%@ OutputCache Duration="100" VaryByParam="none" VaryByCustom="sessionid" %>


來把 SessionID (Cookie:ASP.NET_SessionId) 當作 Cache Key.

 

HEMiDEMi Technorati Del.icio.us MyShare個人書籤 Yahoo

0 意見: