繁体   English   中英

如何从Controller中使缓存数据[OutputCache]无效?

[英]How to invalidate cache data [OutputCache] from a Controller?

使用ASP.Net MVC 3我有一个控制器,使用属性[OutputCache]缓存输出

[OutputCache]
public controllerA(){}

我想知道是否可以通过调用另一个控制器使特定控制器的缓存数据(SERVER CACHE)或通常所有缓存数据无效

public controllerB(){} // Calling this invalidates the cache

您可以使用RemoveOutputCacheItem方法。

以下是如何使用它的示例:

public class HomeController : Controller
{
    [OutputCache(Duration = 60, Location = OutputCacheLocation.Server)]
    public ActionResult Index()
    {
        return Content(DateTime.Now.ToLongTimeString());
    }

    public ActionResult InvalidateCacheForIndexAction()
    {
        string path = Url.Action("index");
        Response.RemoveOutputCacheItem(path);
        return Content("cache invalidated, you could now go back to the index action");
    }
}

索引操作响应在服务器上缓存1分钟。 如果您点击InvalidateCacheForIndexAction操作,它将使Index操作的缓存失效。 目前无法使整个缓存无效,您应该根据缓存操作(而不是控制器)执行此操作,因为RemoveOutputCacheItem方法需要缓存的服务器端脚本的url。

您可以使用自定义属性执行此操作,如下所示:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : 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);
    }
}

然后在您的controllerb您可以:

[NoCache]
public class controllerB
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM