如何设置字典中的值类型会话变量?

如何设置字典中的值类型会话变量?

问题描述:

我有下面的代码来获取会话变量值的字典类型。请看下面的代码如何设置字典中的值类型会话变量?

在我的代码,我只是用下面的代码从我的会话变量得到任何值:

string panelOpen = SessionDictionary.GetValue("FORMDATA", "panelOpen"); 

public class SessionDictionary 
{ 
    public static string GetValue(string dictionaryName, string key) 
    { 
     string value = string.Empty; 
     try 
     { 
      if (HttpContext.Current.Session[dictionaryName] != null) 
      { 
       Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session[dictionaryName]; 
       if (form.ContainsKey(key)) 
       { 
        if (!string.IsNullOrEmpty(key)) 
        { 
         value = form[key]; 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Logger.Error("{0}: Error while checking Session value from Dictionary", ex, "SessionDictionary"); 
     } 
     return value; 
    } 
} 

现在我想写信给为特定的会话密钥值的方法,例如

SessionDictionary.SetValue("FORMDATA", "panelOpen") = "First"; 

现在,如果我再次去下面的代码它应该给我“第一”为我的panelOpen键。

string panelOpen = SessionDictionary.GetValue("FORMDATA", "panelOpen"); 

请建议!

+1

为什么你第一次做的containsKey(密钥)和*然后*一个IsNullOrEmpty(钥匙)?我希望这些测试能够逆转。 – 2011-02-04 11:49:53

+1

在SessionState中使用Dictionary时要小心,因为它不可序列化。如果您在会话中使用SQL持久性,这可能会有可伸缩性问题http://stackoverflow.com/questions/4854406/serialization-of-dictionary和http://support.microsoft.com/kb/311209 – StuartLC 2011-02-04 11:56:11

除了行value = form[key];之外,“SetValue”几乎相同。那应该成为form[key] = value;

不需要“将字典重新设置到会话中”,因为对该字典的引用仍然存在于会话中。

例子:

设定值

public static void SetValue(string dictionaryName, string key, string value) 
{ 
    if (!String.IsNullOrEmpty(key)) 
    { 
    try 
    { 
     if (HttpContext.Current.Session[dictionaryName] != null) 
     { 
      Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session[dictionaryName]; 
      if (form.ContainsKey(key)) 
      { 
       form[key] = value; 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     Logger.Error("{0}: Error while checking Session value from Dictionary", ex, "SessionDictionary"); 
    } 
    } 
} 

删除值:

public static void RemoveValue(string dictionaryName, string key) 
{ 
    if (!String.IsNullOrEmpty(key)) 
    { 
    try 
    { 
     if (HttpContext.Current.Session[dictionaryName] != null) 
     { 
      Dictionary<string, string> form = (Dictionary<string, string>)HttpContext.Current.Session[dictionaryName]; 
      form.Remove(key); // no error if key didn't exist 
     } 
    } 
    catch (Exception ex) 
    { 
     Logger.Error("{0}: Error while checking Session value from Dictionary", ex, "SessionDictionary"); 
    } 
    } 
}