ASP.net缓存绝对到期不工作
发布时间:2020-05-24 02:50:58 所属栏目:asp.Net 来源:互联网
导读:我正在HttpContext.Cache中存储一个整数值,绝对过期时间为5分钟.然而,等待6分钟(或更长时间)后,整数值仍然在缓存中(即使绝对过期已经过去也不会被清除).这是我正在使用的代码: public void UpdateCountFor(string remoteIp){ // only returns true the first
|
我正在HttpContext.Cache中存储一个整数值,绝对过期时间为5分钟.然而,等待6分钟(或更长时间)后,整数值仍然在缓存中(即使绝对过期已经过去也不会被清除).这是我正在使用的代码: public void UpdateCountFor(string remoteIp)
{
// only returns true the first time its run
// after that the value is still in the Cache
// even after the absolute expiration has passed
// so after that this keeps returning false
if (HttpContext.Current.Cache[remoteIp] == null)
{
// nothing for this ip in the cache so add the ip as a key with a value of 1
var expireDate = DateTime.Now.AddMinutes(5);
// I also tried:
// var expireDate = DateTime.UtcNow.AddMinutes(5);
// and that did not work either.
HttpContext.Current.Cache.Insert(remoteIp,1,null,expireDate,Cache.NoSlidingExpiration,CacheItemPriority.Default,null);
}
else
{
// increment the existing value
HttpContext.Current.Cache[remoteIp] = ((int)HttpContext.Current.Cache[remoteIp]) + 1;
}
}
我第一次运行UpdateCountFor(“127.0.0.1”)时,它将使用键“127.0.0.1”将1插入到缓存中,从预期的5分钟绝对到期.然后每个后续的运行都会增加缓存中的值.但是,等待10分钟后,它将继续增加缓存中的值.该值永远不会过期,从不会从缓存中删除.这是为什么? 这是我的理解,绝对过期时间意味着该项目将在当时被删除.我做错了吗?我误会了吗? 我期望在5分钟之后从Cache中删除该值,但是在重建项目之前,它将保留在该位置. 这一切都在本地机器上的.NET 4.0上运行. 解决方法事实证明这一行:HttpContext.Current.Cache[remoteIp] = ((int)HttpContext.Current.Cache[remoteIp]) + 1; 删除以前的值,并重新插入值为无绝对或滑动过期时间.为了解决这个问题,我不得不创建一个帮助类并使用它: public class IncrementingCacheCounter
{
public int Count;
public DateTime ExpireDate;
}
public void UpdateCountFor(string remoteIp)
{
IncrementingCacheCounter counter = null;
if (HttpContext.Current.Cache[remoteIp] == null)
{
var expireDate = DateTime.Now.AddMinutes(5);
counter = new IncrementingCacheCounter { Count = 1,ExpireDate = expireDate };
}
else
{
counter = (IncrementingCacheCounter)HttpContext.Current.Cache[remoteIp];
counter.Count++;
}
HttpContext.Current.Cache.Insert(remoteIp,counter,counter.ExpireDate,null);
}
这将解决问题,并让计数器在绝对时间正确到期,同时仍然允许更新. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – URL重写 – web.config错误
- asp.net-mvc-4 – 如何获取没有隐藏输入的AntiForgeryToken
- 如何在ASP.NET MVC模型中为POST保存选定的DropDownList值?
- asp.net-web-api – 如何在ASP.NET 5和MVC 6中启用跨源请求
- 如何最好地生成CSV(逗号分隔的文本文件)以便下载ASP.NET?
- 从未调用ASP.NET Web API自定义JsonConverter
- asp.net-mvc – 奇怪的MVC问题
- VS 2013 RC中缺少ASP.NET Web窗体脚手架功能
- 如何在ASP.NET MVC中执行图像的Ajax / JQuery上载?
- msbuild – 通过TFS 2015部署ASP.NET 5(vNext)
推荐文章
站长推荐
- asp.net-mvc – 将HttpRequestMessage转换为Http
- asp.net-web-api – Web API中的多态:单端点可能
- asp.net – 从web.config中膨胀时,SmtpClient不会
- 在ASP.NET Identity中添加角色
- asp.net-mvc – Asp.Net MVC Html助手扩展
- asp.net – 有没有一个原因,cshtml不受欢迎
- asp.net-mvc – 如何锁定ASP.NET MVC中的路径?
- asp.net-core – 当返回null而不是控制器中设置的
- 休息 – ASP.NET Web Api路由自定义
- asp.net-mvc-3 – MVC:路由获取/发布到不同的控
热点阅读
