使用保存的会话变量读取和设置变量

时间:2014-03-28 14:09:16

标签: asp.net-mvc asp.net-mvc-3 session sql-server-2008-r2 session-variables

我在会话中添加了用户名,角色和用户ID,会话保存在SQL Server中。如果用户在会话尚未到期时关闭并重新打开浏览器,我如何获取添加到会话中的先前值? 例如,会话中添加了以下值。

 SessionWrapper.currentRequest.UserName = model.UserName;
        SessionWrapper.currentRequest.Role = aRole;
        SessionWrapper.currentRequest.UserId = userId;

用户关闭浏览器并重新打开它;会话未过期。如何恢复会话以使这些变量保持不变?

//This is the object that is wrapped in the session

public class CurrentRequest
    {
        public int UserId { get; set; }
        public string Role { get; set; }
    }

//The session Wrapper

 public class SessionWrapper
            {
                public static CurrentRequest currentRequest
                {
                    get
                    {
                        if (HttpContext.Current.Session["request"] != null)
                        {
                            return (CurrentRequest)HttpContext.Current.Session["request"];
                        }
                        else
                        {
                            return null;
                        }
                    }
                    set
                    {
                        HttpContext.Current.Session["request"] = value;
                    }
                }
            }

// I am saving the following values in the session

  SessionWrapper.currentRequest.UserName = model.UserName;
    SessionWrapper.currentRequest.Role = aRole;
    SessionWrapper.currentRequest.UserId = userId;

The sessionState mode is SQLServer, and I can see data added to the both ASPSTATE tables. here is how I set up the session state in the config file

<sessionState mode="SQLServer" allowCustomSqlDatabase="true" timeout="60" 

cookieless="false" sqlConnectionString="Data Source=(****);Initial Catalog=data1;User ID=****;Password=****;Integrated Security=True" />

1 个答案:

答案 0 :(得分:0)

我的global.asax文件中没有Session_start和Session_end方法。我加了一个,问题就消失了。