ASP.NET "VaryByCustom" page output caching

We all know that the OutputCache directive allows ASP.NET to cache fully-rendered pages. We can instruct ASP.NET to cache different copies based on form variables like this:
<%@ OutputCache Duration=”60” VaryByParam=”ZipCode” %>

Or we can cache based on HTTP Headers like this:
<%@ OutputCache Duration=”60” VaryByParam=”None” VaryByHeader=”User-Agent” %>

The key to creating a custom cache variance is understanding that ASP.NET uses a simple string comparison to determine if a cached result should be returned instead of processing the page. For example, say we want to cache a certain page by SessionID. We add the OutputCache directive like this:
<%@ OutputCache Duration=”60” VaryByParam=”None” VaryByCustom=”SessionID” %>

Now, in global.asax, we must override the GetVaryByCustomString method, like this:

Public override string GetVaryByCustomString(HttpContext context, string arg)
{
  if(arg.ToLower() == “sessionid”)
  {
    HttpCookie cookie = context.Request.Cookies[“ASP.NET_SessionID”];
    if(cookie != null)
      return cookie.Value;
  }
  return base.GetVaryByCustomString(context, arg);
}

That’s it. Simple, elegant, beautiful.

posted @ 2004-07-08 07:53  mp3 swf  阅读(631)  评论(0编辑  收藏  举报