0

There is a sort of "trick" that I've seen around more than once, in order to clear the cache for an MVC app by calling a specific url similar to

http://somewebsite.com/Misc/ClearCache

I used it a couple of times, but honestly I didn't understand exactly how it works and I haven't found any documentation or post about it.

Is there anyone that could explain it a bit, possibly with some related documentation?

Many thanks.

znn
  • 459
  • 7
  • 15

2 Answers2

0

I was wrong in my comment, no Ajax needed.

Here would be your JQuery:

$("#clearCache").click(function () {
    if (!$(this).disabled) {
        $('<iframe id="cacheCleared" src="../../Misc/ClearCache"></iframe>').appendTo('body').hide();
    }
});

Then in your Misc Controller you would have:

public ActionResult ClearCache()
{
    foreach (System.Collections.DictionaryEntry entry in   HttpContext.Cache)
    {
        HttpContext.Cache.Remove((entry.Key).ToString());
    }

    return View();
}

Once you append your iframe, it will attempt to load the content from that source. When it tries to load that source, it will hit your ClearCache in your controller and should clear everything.

EDIT: Add this before you return View(); if you want to avoid building a view for it.

System.Web.HttpContext.Current.Response.End();
interesting-name-here
  • 1,851
  • 1
  • 20
  • 33
0

I am not sure if you are using some plugin or 3rd party library for that. But it is as simple as :

  1. write a web method to clearcache like:

    public void Clearcache() 
    { 
    HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
            HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetNoStore(); 
    }
    
  2. Call method from browser with like controller/actionname :http://somewebsite.com/Controller/ClearCache

If cache is 3rd party you can delete as required in same method

Pranav Singh
  • 17,079
  • 30
  • 77
  • 104