如何获取 HttpRuntime.Cache 对象的到期日期时间? [英] How can I get the expiry datetime of an HttpRuntime.Cache object?
问题描述
是否可以获取 HttpRuntime.Cache
对象的到期时间 DateTime
?
Is it possible to get the expiry DateTime
of an HttpRuntime.Cache
object?
如果是这样,最好的方法是什么?
If so, what would be the best approach?
推荐答案
我刚刚通过了反射器中的 System.Web.Caching.Cache.似乎所有涉及到期日期的内容都标记为内部.我发现唯一可以公开访问它的地方是通过 Cache.Add 和 Cache.Insert 方法.
I just went through the System.Web.Caching.Cache in reflector. It seems like everything that involves the expiry date is marked as internal. The only place i found public access to it, was through the Cache.Add and Cache.Insert methods.
所以看起来你运气不好,除非你想通过反思,除非你真的需要那个日期,否则我不建议这样做.
So it looks like you are out of luck, unless you want to go through reflection, which I wouldn't recommend unless you really really need that date.
但是如果您无论如何都想这样做,那么这里有一些代码可以解决问题:
But if you wish to do it anyway, then here is some code that would do the trick:
private DateTime GetCacheUtcExpiryDateTime(string cacheKey)
{
object cacheEntry = Cache.GetType().GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Cache, new object[] { cacheKey, 1 });
PropertyInfo utcExpiresProperty = cacheEntry.GetType().GetProperty("UtcExpires", BindingFlags.NonPublic | BindingFlags.Instance);
DateTime utcExpiresValue = (DateTime)utcExpiresProperty.GetValue(cacheEntry, null);
return utcExpiresValue;
}
自 .NET 4.5 起 的内部公共 getterHttpRuntime.Cache
被替换为静态变量,因此您需要调用/获取静态变量:
Since .NET 4.5 the internal public getter of the HttpRuntime.Cache
was replaced with a static variant and thus you will need to invoke/get the static variant:
object cacheEntry = Cache.GetType().GetMethod("Get").Invoke(null, new object[] { cacheKey, 1 });
这篇关于如何获取 HttpRuntime.Cache 对象的到期日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!