查询HttpContext.Current.Cache中的项目

max*_*axp 2 c# asp.net caching

将项添加到此缓存中很简单:

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

如果我可以查询缓存并检索每个项目的到期日期,那将是很好的.

这可能吗?据我所知,我只能检索密钥名称.

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

ada*_*ost 5

是的,您可以使用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);
        }
Run Code Online (Sandbox Code Playgroud)