Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear browser cache on browser back button click in MVC4?

Tags:

I know this is a popular question in stackoverflow. I have gone through every same question and I am unable to find the right answer for me. This is my log out controller Action Result

    [Authorize]            public ActionResult LogOut(User filterContext)     {         Session.Clear();         Session.Abandon();         Session.RemoveAll();         Response.Cache.SetCacheability(HttpCacheability.NoCache);         Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));         Response.Cache.SetNoStore();         FormsAuthentication.SignOut();         return RedirectToAction("Home", true);      } 

It didn't work for me. I also tried adding-

<meta http-equiv="Cache-Control" content="no-cache" /> <meta http-equiv="Pragma" content="no-cache"/> <meta http-equiv="Expires" content="0"/>

none of these resolved my issue.

like image 399
Sandy Avatar asked May 02 '13 11:05

Sandy


People also ask

Can you force a browser to clear cache?

But you can bypass the cache and force a complete refresh by using some simple hotkeys: Windows and Linux browsers: CTRL + F5. Apple Safari: SHIFT + Reload toolbar button. Chrome and Firefox for Mac: CMD + SHIFT + R.


2 Answers

The problem with your approach is that you are setting it where it is already too late for MVC to apply it. The following three lines of your code should be put in the method that shows the view (consequently the page) that you do not want to show.

Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1)); Response.Cache.SetNoStore(); 

If you want to apply the "no cache on browser back" behavior on all pages then you should put it in global.asax.

protected void Application_BeginRequest() {     Response.Cache.SetCacheability(HttpCacheability.NoCache);     Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));     Response.Cache.SetNoStore(); } 
like image 77
von v. Avatar answered Oct 27 '22 12:10

von v.


Just set the output cache on the action. I have used this approach in many projects:

[HttpGet, OutputCache(NoStore = true, Duration = 1)] public ActionResult Welcome() {     return View(); } 

The above attribute will basically instruct the browser to get a fresh copy of the page from your controller action if the user navigates back / forward to your view.

You can also define your caching in the web.config and use in conjunction with this attribute to avoid some repetition. See here

like image 25
MarkG Avatar answered Oct 27 '22 13:10

MarkG