我们有这个辅助类来访问会话,但它只存储最后一个值。我无法发现任何错误。
public interface ISessionHelper
{
void AddToSession<T>(string key, T value);
T GetFromSession<T>(string key);
void RemoveFromSession(string key);
}
public class SessionHelper : ISessionHelper
{
private static SessionHelper sessionHelper;
private Dictionary<string, object> sessionCollection;
private const string SESSION_MASTER_KEY = "SESSION_MASTER";
private SessionHelper()
{
if (null == sessionCollection)
{
sessionCollection = new Dictionary<string, object>();
}
}
public static ISessionHelper Instance
{
get
{
if (null == sessionHelper)
{
sessionHelper = new SessionHelper();
}
return sessionHelper;
}
}
public void AddToSession<T>(string key, T value)
{
sessionCollection[key] = value;
HttpContext.Current.Session.Add(SESSION_MASTER_KEY, sessionCollection);
}
public void RemoveFromSession(string key)
{
sessionCollection.Remove(key);
}
public T GetFromSession<T>(string key)
{
var sessionCollection = HttpContext.Current.Session[SESSION_MASTER_KEY] as Dictionary<string, object>;
if (null != sessionCollection)
{
if (sessionCollection.ContainsKey(key))
{
return (T)sessionCollection[key];
}
else
{
return default(T);
}
}
else
{
throw new Exception("Session Abandoned");
}
}
}
对此课程的调用如下:
SessionHelper.Instance.AddToSession(SessionConstants.CURRENT_USER_INFO, user);
我认为初始化类的字典部分会导致问题,但我无法确定它。
或者这可能是问题吗?
void Session_Start(object sender, EventArgs e)
{
CUserRoles userRoles;
string currentUser = HttpContext.Current.User.Identity.Name;
User user = UserManager.GetUserCompleteInfo(currentUser, out userRoles);
if (user != null && user.UserID > 0)
{
SessionHelper.Instance.AddToSession(SessionConstants.CURRENT_USER_INFO, user);
if (userRoles != null)
{
SessionHelper.Instance.AddToSession(SessionConstants.CURRENT_USER_ROLE, userRoles);
}
}
else
{
Response.Redirect("AccessDenied.aspx", true);
}
}
答案 0 :(得分:0)
我会想象,因为sessionCollection
是单身人士的成员,所以有一个角色。我只是删除成员sessionCollection
拉出会话并使用它或在每个方法中根据需要插入它。您的GetFromSession
看起来像是正确的模式。
更简单的方法是这样做。请拨打此电话以获取您的收藏。
private Dictionary<string, object> GetSessionCollection()
{
// add locking
var collection = HttpContext.Current.Session[SESSION_MASTER_KEY] as Dictionary<string, object>;
if (collection == null)
{
collection = new Dictionary<string, object>()
HttpContext.Current.Session[SESSION_MASTER_KEY] = collection;
}
return collection;
}
更新后的AddToSession
public void AddToSession<T>(string key, T value)
{
var sessionCollection = GetSessionCollection();
sessionCollection.Add(key, value);
}