ASP.NET 輸出緩存的移除

十月 19, 2010 by
Filed under: SCJP 

ASP.NET輸出緩存的使用網上已經有很多例子了,這裏主要介紹下如何在後臺管理中移除緩存。

  1.基於頁面緩存

  對於頁面:Default.aspx  如果頁面頂部添加:

  <%@OutputCacheDuration="60″VaryByParam="none"%>

  在後臺管理中要移除很簡單:

  System.Web.HttpResponse.RemoveOutputCacheItem(Page.ResolveUrl(“Default.aspx"));

  2.基於控件

  對於控件WebUserControl.ascx 如果在頂部添加了

  <%@OutputCacheDuration="60″VaryByParam="none"  Shared="true"%>

  在後臺管理中要實現的話有點麻煩,查爾斯提供了壹種解決方法。

  實現如下:

  (1)添加VaryByCustom項,值為Cashgroupclass。

  <%@OutputCacheDuration="60″VaryByParam="none"  Shared="true"  VaryByCustom="Cashgroupclass"%>

  (2)  在Global.asax 中重寫 GetVaryByCustomString 方法,代碼如下:

  代碼

  public override string GetVaryByCustomString(HttpContext context, string arg)

  {

  if (arg == “Cashgroupclass")

  {

  Cache objCache = HttpRuntime.Cache;

  Object _flag = objCache[“Cashgroupclass"];

  if (_flag == null)

  {

  _flag = DateTime.Now.Ticks.ToString();

  objCache.Insert(“Cashgroupclass", _flag);

  }

  return _flag.ToString();

  }

  return base.GetVaryByCustomString(context, arg);

  }

  (3)在後臺管理的移除頁面添加如下代碼:

  Cache objCache = HttpRuntime.Cache;

  if (objCache[“Cashgroupclass"] != null)

  {

  objCache.Remove(“Cashgroupclass");

  }

  當然,您也可以借助這個方法實現控件的緩存更新。對了,查爾斯貼的代碼中有使用DataCache類,是個自己寫的類,可以參考DataCache ,不過裏面重載參數對不上。那就加壹個吧。

  代碼

  public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)

  {

  HttpRuntime.Cache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);

  }

Comments

Tell me what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!





*