C# 缓存字符串24小时

C# 缓存字符串24小时,c#,asp.net-mvc,caching,C#,Asp.net Mvc,Caching,我试图在.NETMVC应用程序中缓存一个字符串24小时。我无法找到使缓存过期的方法。目前,我使用 System.Runtime.Caching.MemoryCache.Default["activeKey"] = "success"; 我通过调用 var activeKey = System.Runtime.Caching.MemoryCache.Default["activeKey"]; if (activeKey != null && (string) activeKey

我试图在.NETMVC应用程序中缓存一个字符串24小时。我无法找到使缓存过期的方法。目前,我使用

System.Runtime.Caching.MemoryCache.Default["activeKey"] = "success";
我通过调用

var activeKey = System.Runtime.Caching.MemoryCache.Default["activeKey"];
if (activeKey != null && (string) activeKey == "success")
{
    return true;
}
然而,我不确定从这里到缓存的方向。我找到了用于滑动和绝对缓存的文档,但我不确定到底要做什么。

添加或现有的
方法是您能得到的最好方法。它们都有一个参数来设置过期(
absoluteExpiration

or
AddOrGetExisting
方法是您可以获得的最佳方法。它们都有一个参数来设置过期(
absoluteExpiration


你检查过这个:
class HackItCacheItem{public DateTime Created{get;set;}公共字符串值{get;set;}}
if DateTime.Now-Created>TimeSpan.FromDays(1)…我想你需要使用
Add()
,它有cacheitempolicy的重载你检查过这个:
class HackItCacheItem{public DateTime Created吗{get;set;}公共字符串值{get;set;}
if DateTime.Now-Created>TimeSpan.FromDays(1)…我认为您需要使用
Add()
,它对CacheItemPolicy有一个重载。根据文档,它说add方法需要7个参数。这很奇怪。啊,这样就可以了,没有前缀。这会对每个人应用缓存吗?不仅仅是基于会话的。是的,缓存是应用程序范围的。根据文档,它说add方法需要7个参数太奇怪了。啊,这样就可以了,没有前缀。这会为每个人应用缓存吗?不仅仅是基于会话的。是的,缓存是应用程序范围的。
System.Runtime.Caching.MemoryCache.Default.Add(
    "activeKey",
    "success",
    new DateTimeOffset(DateTime.Now.AddDays(1))
)