0
if (Session["admin_uname"].ToString() == "")
{
    Response.Redirect("login.aspx");
}
else
{
    string userid = Session["admin_uname"].ToString(); 

}

i have wrote above code for sessions... but problem is if there is any session variable it was working properly

if session is not there it was not redirecting to login page and giving an error like

OBJECT REFERENCE NOT SET.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
PrJa
  • 17
  • 4
  • 1
    Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Aug 11 '13 at 19:32

6 Answers6

2

If there is no session exits then u will not able to compare anything. So check its Null or Not. This is how u check the session.

   if (Session["admin_uname"] == null)
    {
        Response.Redirect("login.aspx");
    }
    else
    {
        string userid = Session["admin_uname"].ToString(); 
    }
Raghubar
  • 2,768
  • 1
  • 21
  • 31
0

When you call ToString() on that null, you get the exception. So check for Null value too. You can try this:-

if (Session["admin_uname"].ToString() == "" || Session["admin_uname"].ToString() == Null)
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Check for nullity before you reference the object, like

if (Session["admin_uname"] != null)

// do something
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

You could use this:

if (String.IsNullOrEmpty(Session["admin_uname"].ToString()))
{
    Response.Redirect("login.aspx");
}
else
{
    string userid = Session["admin_uname"].ToString(); 
} 
Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
Goran Štuc
  • 581
  • 4
  • 15
0

I would do like this:

if (Session["admin_uname"] != null || Session["admin_uname"].ToString() == "")
    Response.Redirect("login.aspx");

string userid = Session["admin_uname"].ToString(); 
afzalulh
  • 7,925
  • 2
  • 26
  • 37
0

One more entry:

string userid = Session["admin_uname"] ?? "";
if (string.IsNullOrEmpty(userid))
{
    Response.Redirect("login.aspx");
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794