ASP.Net – Disable Browser Cache in Asp.Net MVC

Browser cache is the temporary stored offline data that is used to speed up the websites or web applications when next time user visit to that page. It has a lot of advantage like speeding up the sytem.
Not every time browser cache is helpful. In some cases where data is continueously change in a short period of time span it may cause to display the old data and it looks like a bug in the system.

This post refer to solve this problem when you are using Asp.Net MVC.

This code creates a new custom attribute:

Create a class :

public class NoCacheClass : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        base.OnResultExecuting(filterContext);
    }
}

Now you may use your custom attribute for your controller actions for No caching link this.

[NoCache]
public class HomeController : Controller
{
    [NoCache]
    public ActionResult index()
    {
        return View();
    }
}