Furkan Gözükara
Furkan Gözükara

Reputation: 23850

Is this the correct way of accessing session inside classes

Is this the correct way of accessing session variables in classes. I am not talking about aspx pages code behind. I am talking about the classes we made.

 HttpContext.Current.Session["myvariable"]="my variable";

Upvotes: 1

Views: 236

Answers (3)

Łukasz Wiatrak
Łukasz Wiatrak

Reputation: 2767

This code will work, but I recommend wrapping it in some property like this:

MyVariableType MyVariable
{
   get { return (MyVariable)(HttpContext.Current.Session["myvariable"] ?? SomeDefaultOrNullValue); }
   set { HttpContext.Current.Session["myvariable"] = value; }
}

Upvotes: 1

SLaks
SLaks

Reputation: 887807

That code will work.

However, unless your class are dedicated to web UI and will only be used by HTTP handlers, it's poor design; you should avoid coupling your backend logic to ASP.Net.

Upvotes: 3

Frazell Thomas
Frazell Thomas

Reputation: 6111

Yes, this is the best method to access the session object in classes.

Upvotes: 1

Related Questions