asp.net 输出缓存移除的实例代码
2014-10-21来源:易贤网

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

更多信息请查看IT技术专栏

2026公务员·事业单位培训课程试听报名

  • 报班类型
  • 姓名
  • 手机号
  • 验证码
推荐信息