How to turn off the caches in MVC

I've written about different kinds of caching in MVC here, I just wanted to turn off some specific caches in my project and found a way to do that, you can do that by overriding OnResultExecuting:

  1. public class TurnOffCache : ActionFilterAttribute
  2. {
  3.     public override void OnResultExecuting(ResultExecutingContext filterContext)
  4.     {
  5.         filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
  6.         filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
  7.         filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
  8.         filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  9.         filterContext.HttpContext.Response.Cache.SetNoStore();
  10.     }
  11. }

and then simply register this page in global.asax like this:

  1.   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  2.     {
  3.         filters.Add(new TurnOffCache());
  4.     }

Notice that this will remove all of the caches in your application. but in some cases you just want to remove the cache of an action , in these cases you can simply make the NoStroe property as true in caching:

  1. [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
  2. public ActionResult AnAction()
  3. {
  4.     return View();
  5. }

this could be useful When you cache a controller and just want to disable the cache for an action, cheers!

Tags: C# Asp.Net MVC

comments powered by Disqus