这里有奇怪的问题。在 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/