2011-02-04 43 views
0

我有下面的代碼來獲取會話變量值的字典類型。請看下面的代碼如何設置字典中的值類型會話變量?

在我的代碼,我只是用下面的代碼從我的會話變量得到任何值:

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

回答

1

除了行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"); 
    } 
    } 
}