문제

I'm working on a Login session through Visual Basic with asp.net. When the session timeout is complete and I click on another different page it gives me an error, "Object reference not set to an instance of an object." SessionState mode="InProc" Here is the code that I used for the session:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Session("Username") Is Nothing Then
        Label1.Text = "Welcome, " & Session("Username").ToString()
    End If
End Sub
도움이 되었습니까?

해결책

If Session("Username") IsNot Nothing Then
    Label1.Text = "Welcome, " & Session("Username").ToString()
Else
    Response.Redirect("~/Default.aspx")
End If

You need to check for if it's not null before you reference it. You were doing the opposite. You were checking to see if it's null, verifying it was, then referencing it. That's why you get a NullReferenceException. Basically all null reference exceptions are the same, you're trying to perform an operation on an object that is null.

다른 팁

Use a built in function which is exactly what you are looking for :

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 If Not IsNothing(Session("Username")) Then
    Label1.Text = "Welcome, " & Session("Username").ToString()
 End If
End Sub

That's all :=)

Cheers

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top