Blog

Filter posts by Category Or Tag of the Blog section!

How to turn off the caches in asp.net MVC

Monday, 24 February 2014

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!

comments powered by Disqus