mercredi 7 novembre 2018

Can't Access Runtime Cache Using Reflection

I am trying to get the expiry date of a HttpRuntime.Cache object, as per this answer:

https://stackoverflow.com/a/350374/1778169

The method is:

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;
}

When I try to use the above method, the first line won't compile:

An object reference is required for object.GetType()

If I replace Cache.GetType() with HttpRuntime.Cache.GetType() it compiles, but I get null returned from this part:

cacheType.GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).

What am I doing wrong?

I am using .NET 4.5. System.Web.Caching is version 4.0.0.0.





Aucun commentaire:

Enregistrer un commentaire