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

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

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

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

有帮助吗?

解决方案

我找到了我一直在寻找的答案:

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

其他提示

如果您知道要清除哪些页面的缓存,以上内容就可以了。在我的实例(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);
}

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

清除缓存:

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

希望这可以帮助。

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

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

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

然后在注销按钮中单击:

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

唔。您可以在 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 * 也可以工作,因为所有请求都将绑定到相同的缓存依赖项。

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

sqlcache依赖关系 msdn

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top