Reputation: 858
If not, is there a way to make it safe? Even though it populates the class members with what is in session isn't the public class static? That means the class/members could be bounced back and forth when multiple users are accessing the application at the same time...right? What am I missing?
Taken from @M4N here: https://stackoverflow.com/a/621620/158050
public class MySession
{
// private constructor
private MySession()
{
Property1 = "default value";
}
// Gets the current session.
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
// **** add your session properties here, e.g like this:
public string Property1 { get; set; }
public DateTime MyDate { get; set; }
public int LoginId { get; set; }
}
This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:
int loginId = MySession.Current.LoginId;
string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;
DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;
Upvotes: 0
Views: 350
Reputation: 32694
Even though MySession.Current
is static, it's not directly storing data. Instead, it's using HttpContext.Current.Session
which is specific to each user's session and therefore it's as safe as the HttpContext.Current.Session
object normally is.
Upvotes: 2