Asp.net mvc 检查空值时出现空错误

Asp.net mvc 检查空值时出现空错误,asp.net-mvc,vb.net,razor,session-variables,nullreferenceexception,Asp.net Mvc,Vb.net,Razor,Session Variables,Nullreferenceexception,在使用会话变量执行某些操作之前,我尝试测试值。 这是用于初始化的(如您所见),会话(“Chemin”)是一个字符串列表: @If (IsDBNull(Session("Chemin")) Or (ViewContext.RouteData.Values("action") = "Index")) Then @Code Dim lst As New List(Of String)() Session("Chemin") = lst // Initi

在使用会话变量执行某些操作之前,我尝试测试值。 这是用于初始化的(如您所见),会话(“Chemin”)是一个字符串列表:

        @If (IsDBNull(Session("Chemin")) Or (ViewContext.RouteData.Values("action") = "Index")) Then
        @Code Dim lst As New List(Of String)()
        Session("Chemin") = lst  // Initialisation
     End Code
End If
但问题在于这里的测试:

@If (Not IsDBNull(ViewContext.RouteData.Values("action")) AndAlso Not IsDBNull(Session("Chemin")) AndAlso Not Session("Chemin").Contains((ViewContext.RouteData.Values("action").ToString()))) Then
我有时会

System.NullReferenceException

我不明白,因为我只是在测试它,但它给了我一个错误。 所以我的问题是:为什么以及什么时候会发生这种情况?如何解决?
编辑:不是重复的,因为不是一个简单的系统。NullReferenceException

首先:DbNull与null不同(在VB俚语中是
Nothing
),所以如果这样调用它,应该检查该方法
IsDbNull()
是否崩溃:
IsDbNull(Nothing)
。 我想是的,但我不确定。如果是这样,再加上一个空检查,你就可以了

如果问题仍然存在,让我们深入探讨:

类似于
ViewContext.RouteData.Values(“action”)
的表达式链中的所有属性都可以为null。这意味着如果
ViewContext
RouteData
甚至
值都为null,将引发此异常

会话
本身也是如此:它是一种值容器,您可以检查该容器中给定键处的值是否为null。但是如果
会话
本身为null会怎么样?这同样适用于
属性

基本上,这将转换为
null.ElementAt(“Chemin”)
。这将在调用周围的
IsDbNull()
之前崩溃

所以你可以这样检查:

Session Is Nothing OrElse IsDBNull(Session("Chemin"))
' note: you might want to check if the session contains the key before getting a value with it


您应该将所有的
IsDBNull
替换为
IsNothing
,这就是您在本例中所寻找的

    @If (IsDBNull(Session("Chemin"))
无法通过,因此会话(“Chemin”)可能无效

您应该检查
ViewContext
ViewContext.RouteData
ViewContext.RouteData.Values
ViewContext.RouteData.Values(“操作”)
是否只是以防万一

您可以通过以下方式进行操作:

                                                @Code Dim values = ViewContext?.RouteData?.Values End Code
                                        @If (values IsNot Nothing) // And the rest of your tests

尝试将其更改为
ViewContext.HttpContext.Request.QueryString.Get(“操作”)
ToString不能返回System.DbNull,这是IsDbNull比较的结果,您在那里的计算结果总是会返回false。Esko,没有ToString也是一样的,我放在那里是因为我很绝望,我后来才使用它。我同意它是Dumbshank,我得到了相同的错误如果会话为null,可能会重复。我如何取消它的空值?会话可以为空吗?顺便说一句,错误发生在第二个测试上,那么为什么它通过第一个测试而不是第二个?如果第一个测试没有问题,那么您的
会话
属性就不是空的。在这种情况下,您可以关注第二个测试并检查属性链中的空值-这是非常基本的内容,我在这里不会解释。
                                                @Code Dim values = ViewContext?.RouteData?.Values End Code
                                        @If (values IsNot Nothing) // And the rest of your tests