Caching data in ASP.NET MVC. Controller ActionResults and even the JSON Results can be cached.
//This prevents IE and Firefox from caching the results of action methods
public class NoCache : 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();
base.OnResultExecuting(filterContext);
}
}
/*
Now on top of the Controller or the action method do
[NoCache]
e.g.
[NoCache]
public ActionResult MyActionMethod(){}
*/
//Add a filterconfig.cs file in App_Start folder
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
/*We don't want anything in this application cached in the server as most pages are dynamic and should go through
* specific flow so that application will function smoothly
* */
filters.Add(new OutputCacheAttribute
{
VaryByParam = "*",
Duration = 0,
NoStore = true,
});
}
}
//Now put the following line in Global.asax Application_Start method
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
//This should disable caching in entire application
[OutputCache(NoStore=true, Duration=0)]
It can be done directly on the controller or the action methods or we can create CacheProfiles in web.config
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="WebsiteCache" duration="3600" varyByParam="None" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
Now on top of controller or action methods, do
[OutputCache(CacheProfile = "WebsiteCache")]
Internet explorer and Firefox caches by default but chrome doesn't cache by default