简体   繁体   English

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

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

Using ASP.Net MVC 3 I have a Controller which output is being cached using attributes [OutputCache] 使用ASP.Net MVC 3我有一个控制器,使用属性[OutputCache]缓存输出

[OutputCache]
public controllerA(){}

I would like to know if it is possible to invalidate the Cache Data (SERVER CACHE) for a Specific Controller or generally all the Cache data by calling another controller 我想知道是否可以通过调用另一个控制器使特定控制器的缓存数据(SERVER CACHE)或通常所有缓存数据无效

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

You could use the RemoveOutputCacheItem method. 您可以使用RemoveOutputCacheItem方法。

Here's an example of how you could use it: 以下是如何使用它的示例:

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");
    }
}

The Index action response is cached on the server for 1 minute. 索引操作响应在服务器上缓存1分钟。 If you hit the InvalidateCacheForIndexAction action it will expire the cache for the Index action. 如果您点击InvalidateCacheForIndexAction操作,它将使Index操作的缓存失效。 Currently there's no way to invalidate the entire cache, you should do it per cached action (not controller) because the RemoveOutputCacheItem method expects the url of the server side script that it cached. 目前无法使整个缓存无效,您应该根据缓存操作(而不是控制器)执行此操作,因为RemoveOutputCacheItem方法需要缓存的服务器端脚本的url。

You can do that by using a custom attribute, like so: 您可以使用自定义属性执行此操作,如下所示:

[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);
    }
}

Then on your controllerb you can do: 然后在您的controllerb您可以:

[NoCache]
public class controllerB
{
}

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

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