asp.net輸出緩存的使用網(wǎng)上已經(jīng)有很多例子了,這里主要介紹下如何在后臺(tái)管理中移除緩存。
1.基于頁(yè)面緩存
對(duì)于頁(yè)面:default.aspx 如果頁(yè)面頂部添加:
<%@ outputcache duration=60 varybyparam=none %>
在后臺(tái)管理中要移除很簡(jiǎn)單:
system.web.httpresponse.removeoutputcacheitem(page.resolveurl(default.aspx));
2.基于控件
對(duì)于控件webusercontrol.ascx 如果在頂部添加了
<%@ outputcache duration=60 varybyparam=none shared=true%>
在后臺(tái)管理中要實(shí)現(xiàn)的話有點(diǎn)麻煩,在博客園的博問(wèn)請(qǐng)朋友們解答,查爾斯提供了一種解決方法。
實(shí)現(xiàn)如下:
(1)添加varybycustom項(xiàng),值為cashgroupclass。
<%@ outputcache duration=60 varybyparam=none shared=true varybycustom=cashgroupclass %>
(2) 在global.asax 中重寫(xiě) 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)在后臺(tái)管理的移除頁(yè)面添加如下代碼:
cache objcache = httpruntime.cache;
if (objcache[cashgroupclass] != null)
{
objcache.remove(cashgroupclass);
}
當(dāng)然,您也可以借助這個(gè)方法實(shí)現(xiàn)控件的緩存更新。對(duì)了,查爾斯貼的代碼中有使用datacache類,是個(gè)自己寫(xiě)的類,可以參考datacache ,不過(guò)里面重載參數(shù)對(duì)不上。那就加一個(gè)吧。
代碼
public static void setcache(string cachekey, object objobject, datetime absoluteexpiration, timespan slidingexpiration)
{
httpruntime.cache.insert(cachekey, objobject, null, absoluteexpiration, slidingexpiration);
}
最后,感謝朋友們對(duì)我的幫助。
參考:(1):緩存應(yīng)用程序頁(yè)面和數(shù)據(jù)(一)
(2):asp.net緩存
(3):global.asax.cs中的getvarybycustomstring函數(shù)在什么地方調(diào)用
(4):datacache
更多信息請(qǐng)查看IT技術(shù)專欄