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.

1

6 Answers 6

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(); 
    }
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

0

Check for nullity before you reference the object, like

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

// do something

Comments

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(); 

Comments

0

One more entry:

string userid = Session["admin_uname"] ?? "";
if (string.IsNullOrEmpty(userid))
{
    Response.Redirect("login.aspx");
}

Comments

0

You could use this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.