我有vb.net网络应用程序,如果用户登录的所有其他页面工作正常,但我从帐户注销的时间比在所有页面中都出错。我知道页面从cookie获取值,但如果cookie是空的,那么它会变为null&所以导致错误页面
错误:System.NullReferenceException:未将对象引用设置为对象的实例。
任何页面加载的VB代码
Dim var, Type As String
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
Dim LogIn, LogOut, listup As Control
Dim BtnProfile As Button = Page.Master.FindControl("myAccount")
LogIn = Master.FindControl("login")
LogOut = Master.FindControl("logout")
listup = Master.FindControl("list")
'not login
If HttpContext.Current.Request.Cookies("chkusername") Is Nothing Then
listup.Visible = True
LogIn.Visible = True
LogOut.Visible = False
BtnProfile.Visible = False
'login
Else
LogOut.Visible = True
BtnProfile.Visible = True
LogIn.Visible = False
listup.Visible = False
End If
登录页面代码
Dim User, Pass As String
If selectbusinesstype.SelectedValue.ToString = "0" Then
Response.Write("<script language='javascript'>alert('Select login type first');</script>")
ElseIf selectbusinesstype.SelectedValue = "Hospitals" Then
Try
If loginId.Text <> "" And password.Text <> "" Then
Dim str As String = "select * from hospitals where username='" + loginId.Text + "' and Password='" + password.Text + "';"
Dim cmd As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
con.Close()
User = ds.Tables(0).Rows(0)("username")
Pass = ds.Tables(0).Rows(0)("password")
If ds.Tables(0).Rows.Count > 0 Then
If User = loginId.Text.ToString And Pass = password.Text.ToString Then
Response.Cookies("User_Type").Value = "Hospitals"
Response.Cookies("chkusername").Value = loginId.Text
Response.Redirect("hospital-profile.aspx?user=" + Request.Cookies("chkusername").Value)
Else
Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>")
End If
Else
Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>")
End If
Else
Response.Write("<script language='javascript'>alert('Enter All the Details');</script>")
End If
Catch ex As Exception
Response.Write("<br /><br /><br /><br /><br />")
Response.Write(ex)
con.Close()
End Try
答案 0 :(得分:1)
你有以下行,
Dim var, Type As String
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
将其转换为
Dim var, Type As String
If not HttpContext.Current.Request.Cookies("chkusername") Is Nothing Then
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
End If
If not HttpContext.Current.Request.Cookies("User_Type") Is Nothing Then
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
End If