Reputation: 93
I've searched on google but could not find anything suitable. Can anyone provide sample code of how to cache a server-side variable in MVC and have it expire after 5 minutes. I want to use it in the controller class.
Many thanks.
UPDATE: I tried MemoryCache, but it updates everytime I refresh the browser, not every 5 minutes. I display ViewBag.IsTime in the browser.
private bool IsTimeForCountUpdate()
{
var cacheKey = $"MyCacheKeyName";
MemoryCache cache = MemoryCache.Default;
int myCache = 0;
if (cache.Contains(cacheKey))
{
//myCache = (int)cache[cacheKey];
return true;
}
else
{
myCache = 1;
CacheItem cacheItem = new CacheItem(cacheKey, myCache);
cache.Add(cacheItem, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5) });
return false;
}
}
public async Task<ActionResult> Dashboard(int t = 1)
{
ViewBag.IsTime = IsTimeForCountUpdate() ? "YES" : "NO";
...
Upvotes: 0
Views: 2124
Reputation: 21078
MemoryCache
You state that you want to cache a server side variable not the content results. In this case you can take a look at using MemoryCache.
Example:
Let's say you want to cache some data you get frequently from the database:
var cacheKey = "MyCacheKeyName";
MemoryCache cache = MemoryCache.Default;
XYZType myCache = null;
if (cache.Contains(cacheKey))
{
myCache = (XYZType)cache[cacheKey];
}
else
{
myCache = GetDataIWantToCache();
CacheItem cacheItem = new CacheItem(cacheKey, myCache);
cache.Add(cacheItem, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5) });
}
Explanation
The if
block checks to for the existence of your item and returns it if it does.
The else
will create your item (replace GetDataIWantToCache with whatever) since it wasn't found and insert it into the cache for five minutes.
OutputCache
Use the OutputCache attribute if you want to cache content results for an entire controller or individual actions. It has settings for controlling how long and if you want to have a cache per parameter and/or some parameters by using the VaryByParam property.
Some more reading for you on caching in .Net
Upvotes: 4
Reputation: 1177
You can simply use ASP.Net built-in OutputCache.
Duration is in seconds, you can store different caches by parameter using VaryByParam.
[OutputCache(Duration = 300, VaryByParam = "id")]
public ActionResult Index(int? id)
{
return Content(DateTime.Now.ToString());
}
Upvotes: 0