C# Retrieve Cache Expire Date from HttpContext.Current.Cache

6.3k Views Asked by At

I am using .net 4.0 HttpContext.Current.Cache.Add() to insert objects to the Cache of my application. In a .aspx Control Panel page I would like to display all the cached objects with their respective expiring date that I specified when they were inserted. How to do it?

1

There are 1 best solutions below

0
On

If i understood you correcly, you want to display the static expiration date that was inserted, right? If so, all you need is to store your expiration date and pass it to your Control Panel. If you're using asp.net mvc, you could send this date as a property of a ViewModel. Let give you an example of what i'm talking about:

public DateTime InsertItemOnCache(object item, DateTime expiration)
{

    DateTime dateExpiration;
    //Here you construct your cache key. 
    //You can use your asp.net sessionID if you want to your cache 
    //to be for a single user.
    var key = string.Format("{0}--{1}", "Test", "NewKey");

    if (expiration != null)
    {
        dateExpiration = expiration;
    }
    else
    {
        //Set your default time
        dateExpiration = DateTime.Now.AddHours(4);
    }
    //I recommend using Insert over Add, since add will return null if there are
    //2 objects with the same key
    HttpContext.Current.Cache.Insert(key, item, null, dateExpiration, Cache.NoSlidingExpiration);

    return dateExpiration;
}

However if you want your expiration date 'on the fly' you would have to use reflection. For that consult the post that was suggested as comment on your question.