Ehsan Ghanbari

Experience, DotNet, Solutions

How to turn off the caches in asp.net MVC

I've written about different kinds of caching in asp.net 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:

 

public class TurnOffCache : 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();
    }
}

 

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

 

  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new TurnOffCache());
    }

 

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 NoStore property as true in caching:

 

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AnAction()
{
    return View();
}

 

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 and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
How to query over Icollection<> of a type with linq
What's the DDD-lite?
comments powered by Disqus