I have a function in controller which returns a list of countries.I am trying to implement caching in it..so that list is fetched only when empty at server side.I found two ways:
Using OutputCache
[OutputCache(Duration = 86400, Location = OutputCacheLocation.Server,VaryByParam ="none")] public function getelement(){ //return list of country; }
But I am not able to test it maybe because both client and server is myself in this.
Using MemoryCache
private static MemoryCache _cache = MemoryCache.Default; _cache.Add(cacheKey, obj, policy);//MemoryCache(String, NameValueCollection, Boolean)
I am not able to correctly implement 2nd one.
Any suggestions?
Update 1:
ObjectCache cache = MemoryCache.Default;
string cacheKey = "countrylist";
var cacheObject = cache.Get(cacheKey);
if (cacheObject == null)
{
cacheObject = getelement();//returns a list of string type
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60);
cache.Add(cacheKey, cacheObject, policy);
}
I am not able to use cacheObject or access the list which now is of object type.
I tried following solutions:
1. var mylist = (from p in cacheObject.Cast<string>(IQueryable) select p).ToList();
2. List<string> mylist = cacheObject.AsQueryable().Cast<string>().Select(values).ToList();
values.AddRange(mylist);
But I am not able to create a list of string type :(