I am using ASP.NET MVC 4 with WEB API
I have the following action, in the action shown below, my service method makes a db call to DoMagic() method and
Add a reference to System.Runtime.Caching in your project. Add a helper class :
using System;
using System.Runtime.Caching;
public static class MemoryCacher
{
public static object GetValue(string key)
{
MemoryCache memoryCache = MemoryCache.Default;
return memoryCache.Get(key);
}
public static bool Add(string key, object value, DateTimeOffset absExpiration)
{
MemoryCache memoryCache = MemoryCache.Default;
return memoryCache.Add(key, value, absExpiration);
}
public static void Delete(string key)
{
MemoryCache memoryCache = MemoryCache.Default;
if (memoryCache.Contains(key))
{
memoryCache.Remove(key);
}
}
}
Then from your code get or set objects in the cache :
list = (List )MemoryCacher.GetValue("CacheItem1");
and
MemoryCacher.Add("CacheItem1", list, DateTimeOffset.UtcNow.AddYears(1));