I have always stored data for a user (after they logged in) in a Session variable, so I can use that data on any page.
I found out that another way to store information globally is to store it in a class, using { get; set;}
, and then calling that from any page.
Right now, I've used both these methods as a test, and they both work really well:
Session["LoginId"] = rdr["uniqueIdentifier"].ToString();
And
Member.LoginId = rdr["uniqueIdentifier"].ToString();
Where (In Member.cs)
public class Member
{
public static int Challenges { get; set; }
public static int NicknameId { get; set; }
public static string LoginId { get; set; }
public static string FriendsListId { get; set; }
public static void ClearVariables()
{
Challenges = 0;
NicknameId = 0;
LoginId = null;
FriendsListId = null;
}
}
Global.asax
void Session_End(object sender, EventArgs e)
{
Member.ClearVariables();
}
My question is, is it safe enough to store user data in a class like this, or should I stick with Session
objects?
Updated for Completeness Will this post do something like above, but for multiple users? How to access session variables from any class in ASP.NET?
I found this approach is one of the most easy to use and with least error of chances. I think this is called Facade Design Pattern.
public class SiteSession
{
#region Attributes
private static string _siteSession = "__SiteSession__";
#endregion
#region Constructor
private SiteSession()
{
}
#endregion
#region CurrentSession
public static SiteSession Current
{
get
{
SiteSession session = HttpContext.Current.Session[_siteSession ] as SiteSession;
if (session == null)
{
session = new SiteSession();
HttpContext.Current.Session[_siteSession ] = session;
}
return session;
}
}
#endregion
#region SessionProperties
public sherserve.CustomTypes.UserTypes UserType { get; set; }
public int UserID { get; set; }
public String StaffID { get; set; }
public String Position { get; set; }
public String StaffName { get; set; }
public int TimeZone { get; set; }
public String DealerId { get; set; }
public String DealerPosition { get; set; }
public String DealerName { get; set; }
public int DealerFirmId { get; set; }
public String ClientId { get; set; }
public String ClientName { get; set; }
public String ClientBusiness { get; set; }
public String CountryCode { get; set; }
public int ClientFirmId { get; set; }
#endregion
}
Values can be store in Session like this:
SiteSession.Current.UserType = user.UserType;
And Can be obtain like this :
int userId= SiteSession.Current.UserID;
It is type safe as well.
In your case it is not safe at all since static variables in asp.net are common to all users.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With