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 :(
OutputCacheis the ability to do client-side (i.e. browser caching) - which means the browser doesn't need to ask for the resource from your server. Is that of use to you?its better to save the list in server's cacheOutputCachecan do both (client and server caching). Plus it can cache on any downstream server (e.g. proxy - msdn.microsoft.com/en-us/library/…). Plus if you later add a CDN you will get improved load times again. Honestly, if you are trying to cache the entire http request you should strongly considerOutputCache. That is what it is for.