Session variables in a Public Class?

G

Guest

Hi,

How can I access a session variable within a Public Class?
I have tried the below code, but I get a server error "Object reference not
set to an instance of an object".

System.Web.HttpContext.Current.Session.Add("myKey", "myValue")
Dim a As String
a = System.Web.HttpContext.Current.Session.Item("myKey")

Thanks,
Thomas Andersson
 
M

Mark Rae

message
Try this:

System.Web.HttpContext.Current.Session("myKey") = "myValue"
Dim a As String
a = System.Web.HttpContext.Current.Session("myKey").ToString()
 
G

Guest

Hi,

Thank you for your suggestion, but this code generate the same error "Object
reference not set to an instance of an object".

Best regards,
Thomas Andersson
 
M

Mark Rae

Thank you for your suggestion, but this code generate the same error
"Object
reference not set to an instance of an object".

Does the error occur on the 1st or 3rd line?
 
M

Mark Rae

In both lines, if I remove the first line the error occur in the 3rd
line...

Hmm - presumably, you can access the Session object from other places i.e.
an ASPX page's code-behind...?
 
G

Guest

Hi Mark,

I can access the session variables from all my aspx pages in the code behind.
But in the public class it is not possible...
I can also access the session variables in the Global.asax, except in the
Sub Application_BeginRequest.
What can be the problem?

Best regards,
Thomas Andersson
 
G

Guest

Hi Juan T. Llibre,

Thank's for the information...
But should it not be possible to access the session variables in a public
class?

Best regards,
Thomas Andersson
 
J

Juan T. Llibre

You are accessing the session variables in the code behind.
i.e., you can set and get session variables in code.

What else do you want to do with session variables in code ?
Where else, if not in code-behind, do you want to access them from ?




Juan T. Llibre
ASP.NET MVP
http://asp.net.do/foros/
Foros de ASP.NET en Español
Ven, y hablemos de ASP.NET...
======================
 
G

gerry

from a class that exists in an external class library and that is not
derived from Page or IHttpHandler or IHttpModule etc
 
J

Juan T. Llibre

Given that Session is a property set via System.Web.UI.Page,
you'll have a hard time implementing a class which is not
derived from Page and which enables Session management.

You might find it worthwhile to read through the
several Session projects at the Code Project :

http://www.codeproject.com/aspnet/#Sessions+and+Session+State

They'll give you an idea of what others have attenmpted to do.



Juan T. Llibre
ASP.NET MVP
http://asp.net.do/foros/
Foros de ASP.NET en Español
Ven, y hablemos de ASP.NET...
======================
 

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

Top