5

I want to clear the browser cache in MVC application.

I added the below code on my .cshtml page and its working for IE and Firefox.

    Response.ExpiresAbsolute = DateTime.Now;
    Response.Expires = 0;
    Response.CacheControl = "no-cache";
    Response.Buffer = true;
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.UtcNow);
    Response.Cache.SetNoStore();
    Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

I am looking for a solution which will work on chrome as well.

Sanoop
  • 119
  • 1
  • 2
  • 11

2 Answers2

4

Use the Following Attribute:

public class NoCacheAttribute : ActionFilterAttribute
{        
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        if (filterContext == null) throw new ArgumentNullException("filterContext");

        var cache = GetCache(filterContext);

        cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        cache.SetValidUntilExpires(false);
        cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        cache.SetCacheability(HttpCacheability.NoCache);
        cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }

    /// <summary>
    /// Get the reponse cache
    /// </summary>
    /// <param name="filterContext"></param>
    /// <returns></returns>
    protected virtual HttpCachePolicyBase GetCache(ResultExecutingContext filterContext)
    {
        return filterContext.HttpContext.Response.Cache;
    }
 }

}

Simply add this to your base controller :

[NoCache]
public BaseController: Controller
  • i think he is looking to do it after a specific event/action, like when an update takes place. – Alexandros B Apr 28 '13 at 12:16
  • Then, Use that on : public override void OnResultExecuted Event. –  Apr 29 '13 at 07:28
  • This only works on a view that you do not want to go back to. If a user navigates through multiple pages and then logs out this won't work because he can log out from any page and then to make this work the dev will have to use this on all views and that means no caching and hence more hits on the server – Mohit Shah Mar 04 '16 at 05:14
0

This worked for me when cachebusting ajax requests on Chrome.

Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
Response.AddHeader("Expires", "Fri, 01 Jan 1990 00:00:00 GMT");
Response.AddHeader("Pragma", "no-cache");
Alexandros B
  • 1,881
  • 1
  • 23
  • 36