asp.net - iisExpress 本地 httpruntime.cache 始终为 null

标签 asp.net caching iis-express httpruntime.cache

这里有奇怪的问题。在 asp.net webforms (4.5/4.7) 中的本地开发中,我发现 httpruntime.Cache 始终为 null,即使正确设置也是如此。我在另一个 iis Express 工作站上尝试了它,发现了相同的行为,即使使用测试仪单页网页也是如此。生产 IIS 7.5 中的同一页面可以正常工作,并从缓存中存储和交付。具体代码如下,但我尝试过一个测试器在 httpruntime.Cache 中存储一个简单的字符串。

var cache = System.Runtime.Caching.MemoryCache.Default;
var luCacheKey = "lu_" + dsName;

var ic = HttpRuntime.Cache.Get(luCacheKey) as ICollection;
if (ic == null) {

来自测试人员

var item = HttpRuntime.Cache.Get("x");
if (item == null)
{
    HttpContext.Current.Cache.Insert("x", "test" , null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
    Response.Write("added to cache<br>");
}
else {
    Response.Write("already in cache");
}

所以,我想知道 web.config 中是否有一些我可以查看的内容,或者这是预期的 IIS Express 行为?请注意,System.runtime.Caching 确实可以正常工作。

var cache = System.Runtime.Caching.MemoryCache.Default;
var ic = cache[luCacheKey] as ICollection;
if (ic == null)
{
var filterCriteria = new BinaryOperator("LookupGroup", dsName, BinaryOperatorType.Equal);
var lookups = xpoSession.GetClassInfo(typeof(Lookups));
ic = xpoSession.GetObjects(lookups, filterCriteria, new SortingCollection(), 0, 0, false, false);
var cachePolicy = new System.Runtime.Caching.CacheItemPolicy() { AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(30) };
cache.Add(new System.Runtime.Caching.CacheItem(luCacheKey, ic), cachePolicy);

最佳答案

您错误地将对象添加到缓存中。

按照文档并放置 DateTime.UtcNow,而不是 DateTime.Now。这解决了一个常见问题,即您的计算机处于“非零”时区,这会阻止缓存的内部逻辑正确管理您的过期时间。

来自文档

To avoid possible issues with local time such as changes from standard time to daylight saving time, use UtcNow rather than Now for this parameter value.

https://msdn.microsoft.com/en-us/library/4y13wyk9(v=vs.110).aspx

关于asp.net - iisExpress 本地 httpruntime.cache 始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45255259/

相关文章:

asp.net - IIS Express 命令行 ASP.NET MVC 6 beta 8

c# - 在 Visual Studio 中设置 SSL 证书

c# - 我如何在 c# 中使用 Microsoft.Office.Interop.Excel.Application 写入 excel

c# - 可以在 C# 连接器中使用 MySQL @session 变量吗?

c# - 为什么 asp.net 使用 GUID 列而不是 bigint

amazon-web-services - 如何以编程方式获取 'distribution-id' 以使云端缓存无效?

c# - 如何在 asp .net IIS 7 中实现条件 app_offline.htm

javascript - 为用户提供对离线 HTML5 网络应用程序的访问

c# - asp.net 核心数据保护 : An exception was thrown while deserializing the token

c# - WebApplication 在 IIS Express 上运行良好,但在本地 IIS 上运行不正常