Access Session values from static properties of static class

时间:2018-03-09 19:12:42

标签: c# asp.net

I want to use Session values from static properties of a static class which is declared in another referenced project. Some of the properties are per application and some are per user:

public class MyClass
{
    public static string var1 { get; set; } //Always static
    public static string var2 { get; set; } //Need to use Session[Var2]
    public static string var3 { get; set; } //Always static
    public static string var4 { get; set; } //Need to use Session[Var4]
}

2 个答案:

答案 0 :(得分:1)

public class MyClass
{
  public static string var2 
  {
     get { return (string)System.Web.HttpContext.Current.Session["KEY_VAR2"]; }
     set { System.Web.HttpContext.Current.Session["KEY_VAR2"] = value; } 
  }
}

答案 1 :(得分:0)

如果我正确理解了您的问题,您希望将所有用户的会话值存储在集合中。因此,会话是为每个用户提供的。您可以为每个用户创建静态字典并存储会话值。

public class MyClass
{
    public static string var1 { get; set; } //Always static
    public static Dictionary<string,string> var2Dict = new Dictionary<string, string>();
    public static string var3 { get; set; } //Always static
    public static Dictionary<string, string> var4Dict = new Dictionary<string, string>();
}

然后将user的会话值添加到字典中;

MyClass.var2Dict.Add(HttpContext.Current.User.Identity.Name, (string)HttpContext.Current.Session["var2"]);