Q: Check if user is logged in using sessions I want to check if a user is logged in and if they are, deny them access to the registration and login pages. When a user logs in I'm setting these session variables:
HttpContext.Current.Session["LoggedIn"] = true;
HttpContext.Current.Session["FullName"] = (string)Reader["FirstName"] + " " + (string)Reader["LastName"];
Response.Redirect("Default.aspx");

And I'm checking them at the top of the register and login pages like so:
if ((bool)HttpContext.Current.Session["LoggedIn"])
{
    Response.Redirect("Default.aspx");
}

However, when I try to go to the page while not logged in this exception gets thrown:

Object reference not set to an instance of an object.

I'm assuming it's ebcause the LoggedIn key doesn't exist because I only create it after a successful login.
So, how can I check if the LoggedIn key exists and if it doesn't, redirect the user to Default.aspx?
Thanks!

A: I think you can do a simple null check on this like....
if (HttpContext.Current.Session["LoggedIn"] != null)
{
   // once inside this loop
   // you can now read the value from Session["LoggedIn"]
   Response.Redirect("Default.aspx");
}


A: you need to make shure that the object is not null before unboxing it 
if(HttpContext.Current.Session["LoggedIn"]!=null)
{

  if ((bool)HttpContext.Current.Session["LoggedIn"])
   {
    Response.Redirect("Default.aspx");
    }
}


A: Why to avoid the default webforms authentication model altogether? Simply use web.config to define a restricted area, set all the settings correctly and you won't have to perform checks like this for every page.
But, if you want to reinvent the wheel....
You check for something that probably doesn't exist yet. You must modify your if-statement like this:
bool isLoggedIn = (HttpContext.Current.Session["LoggedIn"] == null ? false : (bool)HttpContenxt.Current.Session["LoggedIn"];

if (isLoggedIn)
{
    Response.Redirect("Default.aspx");
}

