0

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!

James Dawson
  • 5,309
  • 20
  • 72
  • 126
  • HttpContext.Current.Session["LoggedIn"] != null will tell you if there is any 'LoggedIn' in the session – Darren Wainwright Nov 14 '12 at 17:08
  • The answers on this question are correct if your goal is to safely check a session value. You may want to look into FormAuthentication to avoid the security problems that come with this authetication strategy, in my experience, the level of effort often turns out to be comparable or less to use Forms Auth (or the like) – MatthewMartin Nov 14 '12 at 17:12

3 Answers3

2

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");
}
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • i have an issue in Jquery-TokenInput.. Please check this link and give me a solution if u can..http://stackoverflow.com/questions/13558856/what-should-be-the-correct-response-from-web-service-to-display-the-jquery-token – Xavier Nov 26 '12 at 05:41
2

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");
    }
}
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
0

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");
}
walther
  • 13,466
  • 5
  • 41
  • 67