ASP.NET输出缓存的移除

来源:互联网 发布:怎样在淘宝上找大麻 编辑:程序博客网 时间:2024/05/21 22:21

 ASP.NET输出缓存的使用网上已经有很多例子了,这里主要介绍下如何在后台管理中移除缓存。

1.基于页面缓存

对于页面:Default.aspx 如果页面顶部添加:

<%@OutputCacheDuration="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);  }


 

原创粉丝点击