I am using the Outpu开发者_StackOverflowtCache attribute in my MVC website as follows:
[OutputCache(Duration = 5000,
VaryByParam = "name;region;model;id;op;content;featured;isStarred;page;size;")]
However sometimes I'd like to bypass the output cache entirely and force a fetch from the database. This is especially true for my test environment where I am continuously loading new data in to the database for testing.
Is there anyway I could bypass the cache in this case?
Thanks.
Instead of specifying all of your output cache parameters inline, in the attribute, you could use an OutputCache profile.
Output Cache profiles allow you to put all of your output cache settings in your web.config, give the profile a name, and then point to that profile from your attribute.
Once you have that set up, you could alter the settings in the web.config you use to debug with so that the caching duration is only 1 second. Obviously you would leave your production web.config file with a much larger duration.
For more information about profiles, check out http://msdn.microsoft.com/en-us/library/hdxfb6cy.aspx
If you wanted to turn it off completely you could use
<caching>
<outputCache enableOutputCache="false" />
</caching>
in your web.config under.system.web. If you wanted to do it from code (using a button or something else) you could also do:
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/");
System.Web.Configuration.OutputCacheSection cacheSection = (System.Web.Configuration.OutputCacheSection)config.GetSection("system.web/caching/outputCache");
cacheSection.EnableOutputCache = true/false;
config.Save();
This will probably only work on your dev machine. Most servers are set up to not allow editing that section in the machine.config.
All I needed to to was use a cache dependency. I needed this change to be modified at runtime, so config files were not an option.
Added the following to the action i wanted to have a "no-cache" option on.
Response.AddCacheItemDependency("Pages");
And created the following action that i can call to refresh cache.
public ActionResult RefreshCache()
{
HttpContext.Cache.Insert("Pages", DateTime.Now, null,
DateTime.MaxValue, TimeSpan.Zero,
CacheItemPriority.NotRemovable,
null);
Logger.Info("Cleansed cache");
return RedirectToAction("HubContent");
}
This doesn't exactly answer your question but answers your title (which is not "how to clear an item from the cache"):
You could add a "VaryByParam
":
[OutputCache(Duration=5000,VaryByParam="YourExistingParams;CacheBypass")]
then when you want to bypass the cache you simply pass the CacheBypass
parameter the value of DateTime.UtcNow.Ticks
(or any random thing) => for example: http://localhost/?CacheBypass=1234567890
精彩评论