Access to Session from my class

  • Thread starter Thread starter Dave
  • Start date Start date
D

Dave

Hello.
I have created some class and want to access session data, but there is
error message: The name 'Session' does not exist in the class or namespace
'MyApp.MyWebApp.MyClass'.
So how can access Sesstion from my custom class (class is in separate file,
not in web form)?
 
Depending on the place in your code the session isn't available. For example
in the method Application_BeginRequest in Globals.asax.cs. In this case you
can try to find the session_id in a cookie:

String[] valCookie = Request.ServerVariables.GetValues("HTTP_COOKIE");
for (int i=0; i<valCookie.Length; i++) {
if (valCookie.ToUpper().StartsWith("ASP.NET_SESSIONID")) {
SessionId = valCookie.ToUpper().Replace("ASP.NET_SESSIONID=", "");
break;
}
}
 
Dave said:
Hello.
I have created some class and want to access session data, but there
is error message: The name 'Session' does not exist in the class or
namespace 'MyApp.MyWebApp.MyClass'.
So how can access Sesstion from my custom class (class is in separate
file, not in web form)?

use HttpContext.Current.Session

Note: will work only if you are really in an http-context, in other words your
call is a direct result of a request. (check first if HttpContext.Current is not null)


Hans Kesting
 
Back
Top