我们有这个帮助类来访问会话,但它只存储最后一个值。我无法检测到任何错误。
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);
}
}