Cache.Insert(“”) with absolute expiration off by U

2019-05-08 23:24发布

I have a few asp.net webforms sites, on a production server, that are suddenly having caching problems. The issue is my cache values are not persisting when using the Cache.Insert method. Using Cache["key"] = value does still work though.

For example, when I set a value like this, it is null when I retrieve it.

HttpRuntime.Cache.Insert("CacheTestVal", "Help Me!" null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);

When I set the value like this, I can retrieve the expected value

Cache["CacheTestVal"] = "Help Me!";

I need to be able to set an absolute expiration for the cache value, so I can't use the Cache[""] method. All help is appreciated. Thanks.

Edit: I found that setting the absolute expiration as a UTC datetime does work. I believe the problem is that the server is not converting the absolute expiration to UTC when using DateTime.Now.

HttpRuntime.Cache.Insert("CacheTestVal", "Help Me!" null, DateTime.UtcNow.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);

The date/time and timezone are all set as I would expect on the server, but maybe IIS doesn't recognize this, or there is a bad configuration value somewhere?

1条回答
Emotional °昔
2楼-- · 2019-05-08 23:35

This change in behavior may be caused by having .NET 4.7 installed on the machine. The article linked below says that Microsoft will fix this in the next version of .NET and in the next hotfix.

Quoting parts of the Microsoft page:

Symptoms:

Assume that you have Microsoft .NET Framework 4.7 installed on a computer. When you try to insert items into the Cache object by using the Cache.Insert (string, object, CacheDependency, DateTime, TimeSpan) Insert overload method, you may notice that the inserted Cache items expire much earlier or later than the specified DateTime (expiration time).

Cause:

The internal implementation of System.Web.Caching.Cache uses Coordinated Universal Time (UTC) time-stamp for absolute expiration. But this particular Cache.Insert (string, object, CacheDependecy, DateTime, TimeSpan) Insert overload method does not make sure whether the expiration time is converted to UTC. Therefore, expiration for items that are inserted into the Cache object by using this overload will occur earlier or later than expected, depending on the computer time zone difference from Greenwich Mean Time (GMT).

Workaround:

The temporary workaround for this issue is to use either the Cache.Add method or a different Cache.Insert overload method.

Resolution:

This issue will be fixed in the next version of the .NET Framework, and will also be available in the next hotfix for the .NET Framework 4.7.

References:

https://support.microsoft.com/en-us/help/4035412/fix-expiration-time-issue-when-you-insert-items-by-using-the-cache-ins

http://vimvq1987.com/2017/08/episerver-caching-issue-net-4-7/

查看更多
登录 后发表回答