Ehsan Ghanbari

Experience, DotNet, Solutions

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!

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In MVC
Multiple submit buttons in MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus