ASP.NET / VB读/写Cookie - 对象未设置为对象的实例

时间:2015-01-12 09:51:56

标签: asp.net vb.net cookies

所以我有这段代码:

        Try
        If Request.Cookies("curUsrId")("id") Is Nothing Then
            Dim cke As HttpCookie = New HttpCookie("curUsrId")
            cke("id") = CStr(myUser.Id)
            cke.Expires = Now.AddDays(35)
            Response.Cookies.Add(cke)
        Else
            If Request.Cookies("curUsrId")("id") = "2" Then
                grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowAllRecords
                chkPaging.Checked = True
            Else
                grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowPager
                chkPaging.Checked = False
            End If
        End If
    Catch ex As Exception
        lblErrorMsg.Visible = True
        txtErrorTxt.Visible = True
        txtErrorTxt.Text = ex.Message
    End Try

我正在尝试读取/写入cookie,但每次运行时,我都会得到“对象未设置为对象的实例”错误。

有谁知道为什么?


我稍微改了代码,仍然是同样的错误?根据下面的评论,我会检查价值是否为零。

            Try
            If Request.Cookies("curUsrId").Value Is Nothing Then
                Dim cke As HttpCookie = New HttpCookie("curUsrId")
                cke.Value = CStr(myUser.Id)
                cke.Expires = Now.AddDays(35)
                Response.Cookies.Add(cke)
            Else
                If Request.Cookies("curUsrId").Value = "2" Then
                    grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowAllRecords
                    chkPaging.Checked = True
                Else
                    grdIssues.SettingsPager.Mode = DevExpress.Web.ASPxGridView.GridViewPagerMode.ShowPager
                    chkPaging.Checked = False
                End If
            End If
        Catch ex As Exception
            lblErrorMsg.Visible = True
            txtErrorTxt.Visible = True
            txtErrorTxt.Text = ex.Message
        End Try

另一个编辑:

我在Try线上添加了一个断点,猜测它没有击中。 “没有加载符号信息等”。我尝试手动加载DLL,我重建了解决方案等,没有区别?

1 个答案:

答案 0 :(得分:3)

  

您正在获取此异常,因为您正在尝试读取其值   Cookie集合中不存在的cookie。

If Request.Cookies("curUsrId").Value //Here you are trying to read value from cookie wich is not set yet

尝试使用C#

if(Request.Cookies.Get("curUsrId")==null)
{
//Your code to add cookie
}

在VB.Net

If Request.Cookies.Get("curUserId") Is Nothing Then
相关问题