简体   繁体   English

检查空的HttpContext.Current.Cache值

[英]Checking for null HttpContext.Current.Cache value

In the below snippet, I am trying to assign the cache value if the cache value does not already exist. 在以下代码段中,如果缓存值尚不存在,我将尝试分配缓存值。 I get an Object_reference_not_set_to_an_instance_of_an_object error when running the following. 运行以下命令时,出现Object_reference_not_set_to_an_instance_of_an_object错误。 What am I missing? 我想念什么?

if (string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
                HttpContext.Current.Cache[Key] = data;

I looked around on SO but couldnt find something similar. 我环顾四周,但找不到类似的东西。 Maybe I am just not wording my problem correctly. 也许我只是没有正确表达我的问题。

HttpContext.Current could be null. HttpContext.Current可以为null。 HttpContext.Current.Cache[Key] could be null. HttpContext.Current.Cache [Key]可以为null。

If either of those are null, it would result in the error you are getting. 如果这些都不为空,则将导致您得到错误。

You are getting the NullReferenceException because you are trying to call ToString() on a null instance. 之所以得到NullReferenceException,是因为您试图在一个null实例上调用ToString()

You have to check if HttpContext.Current.Cache[Key] is null before calling ToString() 您必须在调用ToString()之前检查HttpContext.Current.Cache[Key]是否为null

if (HttpContext.Current.Cache[Key] == null)
{
   HttpContext.Current.Cache[Key] = data;
}

You should check for null on HttpContext.Current and on HttpContext.Current.Cache[Key] , both of which could be null. 您应该在HttpContext.CurrentHttpContext.Current.Cache[Key]上检查是否为null,两者都可以为null。 Here's a possible solution, as long as you're okay with not setting the cache key if HttpContext.Current is null. 只要您可以在HttpContext.Current为null的情况下不设置缓存键,那么这是一个可行的解决方案。

if (HttpContext.Current != null &&
    (HttpContext.Current.Cache[Key] == null || string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
{
     HttpContext.Current.Cache[Key] = data;
}

I just changed the 'get value, convert to string, compare' logic to just get the value and see if it's null right up front. 我只是更改了“获取值,转换为字符串,比较”的逻辑,以仅获取值,然后查看它是否为null。 Silly me. 傻我

if (HttpContext.Current.Cache[Key] == null)
       HttpContext.Current.Cache[Key] = data;

The " Object_reference_not_set_to_an_instance_of_an_object error" is actually essentially the 'null' value I was looking for... 实际上,“ Object_reference_not_set_to_an_instance_of_an_object错误”实际上是我正在寻找的“空”值...

If they key isn't present, then this would return null : 如果他们不存在密钥,则将返回null

HttpContext.Current.Cache[Key]

You're then blindly calling ToString() on the value from the cache, causing the exception. 然后,您盲目地从缓存中的值调用ToString() ,从而导致异常。

You need to assign the value from the cache to a temporary variable and test it for null before calling ToString() . 您需要在调用ToString()之前将来自缓存的值分配给一个临时变量,并测试它是否为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM