locked
Handling the null reference RRS feed

  • Question

  • User1028962535 posted

    Hello, I would like users to be taken to the login page, if the session variable is nothing, but  I still get this error, how can I fix it? thanks

    Object reference not set to an instance of an object.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    Source Error: 

    My CODE LOOKS LIKE THIS

    Protected Sub Page_Load(sender As Object, e As EventArgs)

    Dim User As String = Session("UserName").ToString()

    If Session("Username") Is Nothing Then

    Response.Redirect("Login.aspx")

    End If

    End Sub

    Thursday, July 26, 2018 12:02 PM

All replies

  • User-1171043462 posted

    You are doing a mistake. You are first converting to String and then checking use following code

    Protected Sub Page_Load(sender As Object, e As EventArgs)
    
    Dim User As String = Convert.ToString(Session("UserName"))
    
    If Not string.IsNullOrEmpty(User) Then
    
    Response.Redirect("Login.aspx")
    
    End If
    
    End Sub

    Convert.ToString will take care of NULL

    Thursday, July 26, 2018 12:12 PM
  • User-369506445 posted

    Hi

    You get an error when using below code

    Dim User As String = Session("UserName").ToString()

    Because your session may be empty and when converting a null to a string you get an error

    Try

    Dim User As String = ""
    
    
    If Session("Username") Is Nothing Then
    User=Session("UserName").ToString()
    Response.Redirect("Login.aspx")
    Thursday, July 26, 2018 12:23 PM
  • User753101303 posted

    Hi,

    Or as it seems you never actually use the value you are retrieving, just drop this line :

    Protected Sub Page_Load(sender As Object, e As EventArgs)
      If Session("Username") Is Nothing Then
        Response.Redirect("Login.aspx")
      End If
    End Sub

    The problem is that you are using Session("UserName").ToString() so you do call a method on the returned object before checking if this object is nothing.

    Not directly related but this info is available as User.Identity.Name and having a copy in session doesn't seems to add any value(it would better to use what ASP.NET offers to handle logged users rather than rolling your own mechanism)

    Thursday, July 26, 2018 12:26 PM
  • User-821857111 posted

    If Session("Username") Is Nothing Then

    Response.Redirect("Login.aspx")

    End If

    Others have explained why calling the ToString method results in a NullRefrenceException, but you should not be using Session to maintain user logins. You should be using Forms Authentication instead.

    Thursday, July 26, 2018 12:27 PM