简体   繁体   中英

Querying items in HttpContext.Current.Cache

Its simple to add items into this cache:

HttpContext.Current.Cache.Add(
    string key,
    Object value,
    CacheDependency dependencies,
    DateTime absoluteExpiration,
    TimeSpan slidingExpiration,
    CacheItemPriority priority,
    CacheItemRemovedCallback onRemoveCallback
    );

It would be great if I could query the cache and retrieve the expiry date of each item.

Is this possible? As far as I can see I can only retrieve the key name.

Reference: http://msdn.microsoft.com/en-us/library/system.web.caching.cache.add.aspx

Yes you can achieve using Reflection.

foreach (var t in Cache)
        {
            System.Collections.DictionaryEntry entry = (System.Collections.DictionaryEntry)t;
            object key = entry.Key;
            object obj = Cache.GetType().GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Cache, new object[] { key, 1 });
            PropertyInfo prop = obj.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance);
            DateTime expire = (DateTime)prop.GetValue(obj, null);
            Response.Write("<br/>" + key + " : " + expire);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM