test session exist

G

Green

Hi,
I want to test whether a sesion exist, what can i do?
I use Session["name"].toString().length == 0 , but it will prompt the
error saying object is not referenced. How can i test Session["name"]
exist?

Thanks in advance!
 
S

SevDer

Green said:
Hi,
I want to test whether a sesion exist, what can i do?
I use Session["name"].toString().length == 0 , but it will prompt
the error saying object is not referenced. How can i test
Session["name"] exist?

Thanks in advance!

Test it against null.
And as in your example, when it is null, it will complain with the given
error message.
 
S

Shiva

First, check for the existance of the item in the session state collection
before accessing its properties:

if (Session["name"] == null)
{
// name does not exist in the Session state collection.
}
else
{
// Access Session["name"] here...
}

Hope I got the question correctly.

Hi,
I want to test whether a sesion exist, what can i do?
I use Session["name"].toString().length == 0 , but it will prompt the
error saying object is not referenced. How can i test Session["name"]
exist?

Thanks in advance!
 
K

Kevin Spencer

And BTW, on the server side, the Session ALWAYS exists - unless it takes
longer than 20 minutes for the Page to process. Just want to make sure
there's no confusion between the Session Collection and its members.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
I get paid good money to
solve puzzles for a living
 
Joined
Sep 21, 2011
Messages
2
Reaction score
0
check whether session name exists

Its difficult to check whether a session name exists or not..
Because we cannot use a session instance name before it is being declared, means assigning the value to it. So it is better to use the following code. It is very bad programming. but if you want you can use it.

try
{
string data = Session["sessionIds"].tostring();
}
catch(Exception ex)
{
// Do your handling code. ie, if you want to set the session value set here.
}


the idea behind is that using the session variable before declaring the value will thow an error. By this we can make sure that the session variable is not existing.
If you want more specific just check what error throwing in this scenario and check whether the error is same as you required error and do the handling code.
make sure to check whether the error is not coming from any other reasons.
Usually the error will be "object reference not set to an instance of the object".
Hope this will help some one..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top