清除ASP.NET中的页面缓存

时间:2008-08-14 19:39:32

标签: c# asp.net outputcache

对于我的博客,我想使用输出缓存来保存一个特定帖子的缓存版本大约10分钟,这很好......

<%@OutputCache Duration="600" VaryByParam="*" %>

但是,如果有人发表评论,我想清除缓存,以便刷新页面并查看评论。

我如何在ASP.Net C#中执行此操作?

8 个答案:

答案 0 :(得分:48)

我找到了我想要的答案:

HttpResponse.RemoveOutputCacheItem("/caching/CacheForever.aspx");

答案 1 :(得分:39)

如果您知道要清除缓存的页面,则上述情况很好。在我的实例(ASP.NET MVC)中,我引用了来自全世界的相同数据。因此,当我做[保存]时,我想清除缓存网站。这对我有用:http://aspalliance.com/668

这是在OnActionExecuting过滤器的上下文中完成的。它可以通过在BaseController中重写OnActionExecuting或其他东西来轻松完成。

HttpContextBase httpContext = filterContext.HttpContext;
httpContext.Response.AddCacheItemDependency("Pages");

设定:

protected void Application_Start()
{
    HttpRuntime.Cache.Insert("Pages", DateTime.Now);
}

次要调整: 我有一个助手添加“flash消息”(错误消息,成功消息 - “此项已成功保存”等)。为了避免闪存消息出现在每个后续的GET上,我必须在写入flash消息后失效。

清除缓存:

HttpRuntime.Cache.Insert("Pages", DateTime.Now);

希望这有帮助。

答案 2 :(得分:5)

使用Response.AddCacheItemDependency清除所有输出缓存。

  public class Page : System.Web.UI.Page
  {
    protected override void OnLoad(EventArgs e)
    {
        try
        {
            string cacheKey = "cacheKey";
            object cache = HttpContext.Current.Cache[cacheKey];
            if (cache == null)
            {
              HttpContext.Current.Cache[cacheKey] = DateTime.UtcNow.ToString();
            }

            Response.AddCacheItemDependency(cacheKey);
        }
        catch (Exception ex)
        {
            throw new SystemException(ex.Message);
        }

        base.OnLoad(e);
    }     
 }



  // Clear All OutPutCache Method    

    public void ClearAllOutPutCache()
    {
        string cacheKey = "cacheKey";
        HttpContext.Cache.Remove(cacheKey);
    }

这也可以在ASP.NET MVC的OutputCachedPage中使用。

答案 3 :(得分:3)

在母版加载事件中,请写下以下内容:

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

并在注销按钮中单击:

Session.Abandon();
Session.Clear();

答案 4 :(得分:1)

嗯。您可以在OutputCache项目上指定VaryByCustom属性。 this的值作为参数传递给您可以在global.asax中实现的GetVaryByCustomString方法。此方法返回的值用作缓存项的索引 - 例如,如果您返回页面上的注释数,则每次添加注释时都将缓存新页。

需要注意的是,这实际上并没有清除缓存。如果博客条目的评论使用量很大,那么使用此方法可能会导致缓存大小爆炸。

或者,您可以将页面的不可更改位(导航,广告,实际博客条目)实现为用户控件,并在每个用户控件上实现部分页面缓存。

答案 5 :(得分:1)

如果你将“*”更改为缓存应该改变的参数(PostID?),你可以这样做:

//add dependency
string key = "post.aspx?id=" + PostID.ToString();
Cache[key] = new object();
Response.AddCacheItemDependency(key);

当有人添加评论时......

Cache.Remove(key);

我想即使使用VaryByParam *也可以使用,因为所有请求都会依赖于相同的缓存依赖关系。

答案 6 :(得分:1)

为什么不在posts表上使用sqlcachedependency?

sqlcachedependency msdn

这样你就不会实现自定义缓存清除代码,而只是在db中内容发生变化时刷新缓存?

答案 7 :(得分:-1)

HttpRuntime.Close() ..我尝试了所有方法,这是唯一适用于我的方法

相关问题