簡體   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