如何在asp mvc中清除指定控制器中的缓存?

tes*_*der 6 .net c# asp.net asp.net-mvc caching

可能重复:
如何以编程方式清除控制器操作方法的outputcache

如何清除指定控制器中的缓存?

我尝试使用几种方法:

Response.RemoveOutputCacheItem();
Response.Cache.SetExpires(DateTime.Now);
Run Code Online (Sandbox Code Playgroud)

没有任何影响,它不起作用.:(可能存在任何方式获取控制器缓存中的所有键并明确删除它们?在哪个重写的方法我应该执行清除缓存?以及如何做到这一点?

有什么想法吗?

dov*_*ove 8

你有没有尝试过

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult DontCacheMeIfYouCan()
{

}
Run Code Online (Sandbox Code Playgroud)

如果这不适合你,那么Mark Yu建议的自定义属性.


小智 6

试试这个:

把它放在你的模型上:

public class NoCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

并在您的特定控制器上:例如:

[NoCache]
[Authorize]
public ActionResult Home()
 {
     ////////...
}
Run Code Online (Sandbox Code Playgroud)

来源:原始代码

  • 这有效,但不是立即生效,需要等待最后一个缓存过期。 (2认同)