System.Web.Caching.Cache throws null exception in a model

谁说我不能喝 提交于 2019-12-05 12:49:23

You shouldn't use the Cache type to initialise your own instance:

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Without looking directly into why you would get a null reference exception, and I've ran into this problem before, this is tied in with the infrastructure and lifecycle of a web application:

One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.

Bottom line, don't use the System.Web.Caching.Cache type directly in this way - either access an existent cache instance or use an alternative like the Caching Application Block of the Enterprise Library.

As Grant noted above the System.web.caching.cache stores ASP.NET internal data (like bundles that have been built in the App_start).

Use the System.Runtime.Caching instead. here's the walkthrough on MSDN

Here's a snippet: `

using System.Runtime.Caching;

...

ObjectCache cache = MemoryCache.Default;
var test = "hello world";
cache["greeting"] = test;
var greeting = (string)cache["greeting"];

`

In ASP.NET 4, caching is implemented by using the ObjectCache class. read more on MSDN

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!