Search code examples
asp.net-mvc-3cachingoutput-caching

How do I turn off caching for my entire ASP.NET MVC 3 website?


Like the question says, I wanted to know if it's possible to turn off caching on all controllers and actions for my entire site. Thanks!


Solution

  • Create a Global Action Filter and override OnResultExecuting():

    public class DisableCache : 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 register this in your global.asax, like so:

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

    In summation, what this does is create a Global Action Filter so that implicitly this will be applied to all Controllers and all Actions.