【问题标题】:C# Retrieve Cache Expire Date from HttpContext.Current.CacheC# 从 HttpContext.Current.Cache 中检索缓存过期日期
【发布时间】:2012-08-18 00:59:29
【问题描述】:

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

【问题讨论】:

标签: c# caching httpcontext.cache


【解决方案1】:

如果我理解正确,您想显示插入的静态到期日期,对吗?如果是这样,您只需要存储到期日期并将其传递到您的控制面板。如果您使用的是 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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2019-07-22
    • 2015-06-20
    • 2010-12-17
    • 2017-07-10
    • 1970-01-01
    相关资源
    最近更新 更多