萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> asp.net編程 >> ASP.NET 輸出緩存移除的實例代碼

ASP.NET 輸出緩存移除的實例代碼

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

  1.基於頁面緩存

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

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

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

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

  2.基於控件

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

  <%@ OutputCache Duration="60" VaryByParam="none" Shared="true"%>

  在後台管理中要實現的話有點麻煩,在博客園的博問請朋友們解答,查爾斯提供了一種解決方法。

  實現如下:

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

  <%@ OutputCache Duration="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);

  }

  最後,感謝朋友們對我的幫助。

  參考:(1):緩存應用程序頁面和數據(一)

  (2):ASP.NET緩存

  (3):Global.asax.cs中的GetVaryByCustomString函數在什麼地方調用

  (4):DataCache

copyright © 萬盛學電腦網 all rights reserved