通过静态对象的静态属性访问asp.net会话变量是否安全?

通过静态对象的静态属性访问asp.net会话变量是否安全?

这就是我的意思:

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; } } } 

userA可以通过这种方式访问​​userB的会话数据吗?

是的,这种方式很好 – 只要确保你这样做:

 public static class SessionHelper { private static HttpSession sess = HttpContext.Current.Session; public static int Age { get { return (int)sess["Age"]; } set { sess["Age"] = value; } } } 

正如我所见,这种方式向另一个用户显示一个用户的会话数据。 (尽管在ASP.NET 1.1中)

恕我直言,这实际上是一个很好的方法。 它是类型安全的,添加可以让您以最小的影响更改事物的级别抽象。

您可能会更改某些内容的示例,如果您确定某个状态应该移动到缓存,甚至数据库与缓存相结合,这些都需要额外的线程同步,但都可以由此类的内部处理。 您可以考虑将类的名称更改为特定于会话的内容。

我对您的特定示例的一个注释是您应该检查Session变量是否为null并返回适当的默认值,断言或引发信息性exception(如果是)。 以防在设置属性之前读取属性。

实际上,这是我的“基础”SessionClass。

 using System; using System.Collections.Generic; using System.Linq; using System.Web; public static class CSession { private static readonly string zE = ""; private static readonly string CrLF = Environment.NewLine; private static bool bStopHere = true; ///  /// Get a session variable ///  ///  ///  public static object Get(string pSessionKey) { object t = null; if (HttpContext.Current.Session[pSessionKey] != null) { t = (object)HttpContext.Current.Session[pSessionKey]; } return t; }//object Get(string pSessionKey) ///  /// Set a session variable ///  ///  ///  public static void Set(string pSessKey, object pObject) { HttpContext.Current.Session.Remove(pSessKey); HttpContext.Current.Session.Add(pSessKey, pObject); }//void Set(string pSessionKey, object pObject) public static string GetString(string pSessKey) { string sTemp = zE; object t = Get(pSessKey); if (t != null) { sTemp = (string)t; } else { sTemp = zE; } return sTemp; }//string GetString(string pSessionKey) public static int GetInt(string pSessKey) { int s = 0; object t = Get(pSessKey); if (t != null) { s = (int)t; } return s; }//int GetInt(string pSessionKey) public static Int32 GetInt32(string pSessKey) { Int32 s = 0; object t = Get(pSessKey); if (t != null) { s = (Int32)t; } return s; }//Int32 GetInt32(string pSessionKey) public static bool GetBool(string pSessKey) { bool s = false; object t = Get(pSessKey); if (t != null) { s = (bool)t; } return s; }//bool GetBool(string pSessionKey) }//static class CSession