Session variable: Error: Object reference not set as (...)

1

Good! In a previous question I wanted to know how to keep a variable for the whole site and be able to use it when needed: Previous question

But now I'm getting this error very often ...

I tried this and it does not work, among many other tests I did, like adding:

//prueba 1
      if (per_App0 == 0 || per_App0 == null)
        {
            FormsAuthentication.RedirectToLoginPage();
        }
// prueba 2
    per_App0 = new (int)Session["per_App0"];
//prueba 3
    new per_App0 =  (int)Session["per_App0"];

This error does not appear immediately the page is loaded, if I log in and go to the page it works normally, but after a while X when the page refreshes the error appears, so I guess it is as if the session, but if I give back and go back to another page I realize that the session is still active because it does not ask for a password or return to the login.

    
asked by Vulpex 02.11.2017 в 14:35
source

1 answer

1

Try converting the object to Nullable<int> , instead of int only:

  int? per_App0 = (int?)Session["per_App0"];

Session["per_App0"] returns null if it has no assigned object in that index and since the data type int does not accept null, it throws the NullReferenceException . Converting it to nullable, we indicate that it can accept null, in case there is no number.

It is also good to note that a int will never equal null unless declared nullable:

// per_App0 nunca sera null, asi que es innecesario hacer la comparacion
if (per_App0 == 0 || per_App0 == null)
{
    FormsAuthentication.RedirectToLoginPage();
}

Now, if per_App0 were Nullable<int> if it is valid then check for is equal to null:

int? per_App0 = (int?)Session["per_App0"];
if (per_App0 == null || per_App0 == 0)
{
    FormsAuthentication.RedirectToLoginPage();
}

Note: Nullable<int> and int? is the same.

    
answered by 02.11.2017 / 14:41
source