1

我正在使用 .net 4.0HttpContext.Current.Cache.Add()将对象插入到我的应用程序的缓存中。在 .aspx 控制面板页面中,我想显示所有缓存的对象及其各自的到期日期,这些到期日期是我在插入它们时指定的。怎么做?

4

1 回答 1

2

如果我正确理解您,您想显示插入的静态到期日期,对吗?如果是这样,您只需要存储到期日期并将其传递到您的控制面板。如果您使用的是 asp.net mvc,则可以将此日期作为 ViewModel 的属性发送。让你举个例子来说明我在说什么:

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

但是,如果您希望“即时”到期日期,则必须使用反射。为此,请参阅建议作为对您问题的评论的帖子。

于 2012-09-06T18:29:46.733 回答