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();
    }
}

Deepak Arora

Deepak Arora is a Software Developer and working continuously in this field from 2011. He work mainly with Microsoft Technology. He holds a Master's in Computer Application and he is MCTS certified person.

3 thoughts on “ASP.Net – Disable Browser Cache in Asp.Net MVC

  1. Definitely believe that which you said. Your favorite justification seemed to be on the net the easiest thing to be aware of. I say to you, I definitely get irked while people think about worries that they plainly don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side-effects , people can take a signal. Will likely be back to get more. Thanks

  2. I’ve been browsing online greater than 3 hours nowadays, but
    I by no means discovered any attention-grabbing article like yours.
    It is beautiful price sufficient for me. In my opinion, if all website owners and bloggers made good content material as you probably did, the web will
    likely be much more helpful than ever before.

Leave a Reply

Your email address will not be published. Required fields are marked *