如何在 C# 中转换存储在会话中的字典?

How to cast dictionaries stored in the session in C#?

在会话中放置:

HttpContext.Current.Session.Add("_ProjectRights", ProjectRepository.GetProjectRechten(user1.UserId).ToList());

查询:

var data= Db.Users.SingleOrDefault(s => s.UserPk == userId)?.ProjectUser
 .Select(se => new { Key = se.primaryKey1.ToString(), 
Items = string.Join(",", se.ProjectRight.Select(sel => sel.primaryKey2).ToList()) });

IDictionary<string, string> dictionary = data.ToDictionary(pair => pair.Key, pair => pair.Items);

投射失败:

var privilegeLevelsDict = (Dictionary<string, List<string>>)HttpContext.Current.Session["_ProjectRechten"];

投射成功:

var privilegeLevelsDict = (List<KeyValuePair<string, List<string>>>)HttpContext.Current.Session["_ProjectRechten"];

为什么第一个转换不起作用?为什么我必须转换为 KeyValuePairs 列表而不是字典,即使我首先在会话变量中放置了字典?

您正在向会话添加列表,此处:

HttpContext.Current.Session.Add(
    "_ProjectRights", 
    ProjectRepository.GetProjectRechten(user1.UserId).ToList())

注意 ToList() 调用。如果 GetProjectRechten 正在返回一个字典,而这就是您 想要 在会话中的内容(如果它可以序列化)那么您可以删除 ToList() 调用.

HttpContext.Current.Session.Add(
    "_ProjectRights",
    ProjectRepository.GetProjectRechten(user1.UserId))

如果您无法序列化字典但想稍后重新创建它,您可以轻松做到:

var storedValue = HttpContext.Current.Session["_ProjectRechten"];
var list = (List<KeyValuePair<string, List<string>>>) storedValue;
var dictionary = list.ToDictionary(pair => pair.Key, pair => pair.Value);