Is it safe to access asp.net session variables through static properties of a static object?
Here is what I mean:
public static class SessionHelper
{
public static int Age
{
get
{
return (int)HttpContext.Current.Session["Age"];
}
set
{
HttpContext.Current.Session["Age"] = value;
}
}
public static string Name
{
get
{
return (string)HttpContext.Current.Session["Name"];
}
set
{
HttpContext.Current.Session["Name"] = value;
}
}
}
Is it possible that userA could access userB's session data this way?
Very safe, . NET session variables are not the same as cookie variables which can be viewed from the client side, Session variables in this instance are only accessible from the C# code.
The SessionID(eg: 11112222) that this client brings is different. We think that the browser of that client does not accept the SessionID. And finally, we abandon the use of Session, and solved this problem.
Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.
Yes, static values will remain same for all users. if one user is updating that value, then it will be reflected to other users as well.
Yes, that way is fine - just make sure you don't do this:
public static class SessionHelper { private static HttpSession sess = HttpContext.Current.Session; public static int Age { get { return (int)sess["Age"]; } set { sess["Age"] = value; } } }
As ive seen this way show one user's session data to another user. (Albeit in ASP.NET 1.1)
IMHO, this is actually a good approach. It is type safe, add that level abstraction that could allow you to change things with minimal impact.
An example of something you might change, if you decided some state should move to the cache or even the database combined with caching, these would require additional thread synchronization, but could all be handled by the internals of this class. You might consider changing name of the class to something less session specific.
The one comment I would have on your particular example is that you should check that the Session variable is not null
and either return an appropriate default, assert or raise an informative exception if it is. Just in case the property is read before it is being set.
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