在ASP.NET中清除页面缓存

时间:2020-03-05 18:39:44  来源:igfitidea点击:

对于我的博客,我想使用"输出缓存"将某个垂直帖子的缓存版本保存大约10分钟,这很好...

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

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

如何在ASP.Net C#中做到这一点?

解决方案

回答

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

需要注意的是,这实际上并未清除缓存。如果博客条目的评论使用率很高,则此方法可能会使缓存大小爆炸。

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

回答

如果将" *"更改为仅用于缓存的参数(PostID?),则可以执行以下操作:

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

当有人添加评论时...

Cache.Remove(key);

我猜想这甚至可以与VaryByParam *一起使用,因为所有请求都将绑定到相同的缓存依赖项。

回答

我找到了想要的答案:

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

回答

使用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中使用。

回答

为什么不对posts表使用sqlcachedependency?

sqlcachedependency msdn

这样,我们是否不实现自定义缓存清除代码,而只是在数据库中的内容更改时刷新缓存?

回答

如果我们知道要清除哪些页面的缓存,上面的方法就可以了。在我的实例(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消息"(错误消息,成功消息"此项目已成功保存"等)的助手。为了避免Flash消息出现在每个后续的GET上,我必须在编写Flash消息后使其无效。

清除缓存:

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

希望这可以帮助。