我正在使用ASP.Net MVC 3,有一个控制器的输出正在使用属性[OutputCache]
进行缓存。
[OutputCache]
public controllerA(){}
我想知道是否可以通过调用另一个控制器来使特定控制器的缓存数据(服务器缓存)失效,或者是一般地使所有缓存数据失效。
public controllerB(){} // Calling this invalidates the cache
我正在使用ASP.Net MVC 3,有一个控制器的输出正在使用属性[OutputCache]
进行缓存。
[OutputCache]
public controllerA(){}
我想知道是否可以通过调用另一个控制器来使特定控制器的缓存数据(服务器缓存)失效,或者是一般地使所有缓存数据失效。
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");
}
}
Index操作的响应在服务器上缓存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
{
}