【问题标题】:Session Variables Is Null after Redirecting to a New Page重定向到新页面后会话变量为空
【发布时间】:2014-03-27 21:14:12
【问题描述】:

MVS 2012 SQL Server 2008 R2

我有一个使用会话包装器存储在会话中的对象。在登录期间,我初始化对象并适当地设置会话。在对用户进行身份验证后,我将用户重定向到用户索引页面。用户被重定向到索引页面,但会话变量不为空。我不确定为什么会这样。这是我正在做的示例代码。

这是我的网络配置设置。 如果我注释掉这个网络配置部分并再次运行应用程序,它就可以正常工作了。

<sessionState mode="SQLServer" allowCustomSqlDatabase="true" timeout="60" cookieless="false" sqlConnectionString="Data Source=(****);Initial Catalog=data1;User ID=****;Password=****;Integrated Security=True" />

这是包装在会话中的对象

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

这里是会话包装器

 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;
   }
 }

这里我正在检查角色并将用户重定向到相应的页面

CurrentRequest currentRequest = new CurrentRequest();
SessionWrapper.currentRequest = currentRequest;
int userId = login.GetUserId(model.UserName, true);
SessionWrapper.currentRequest.UserName = model.UserName;
string[] roles = Roles.GetRolesForUser(model.UserName);
if (roles.Count() > 0)
{
  string aRole = roles[0];
  switch (aRole)
  {
    case "Admin":
      SessionWrapper.currentRequest.Role = aRole;
      SessionWrapper.currentRequest.UserId = userId; 
.
.

上面的会话变量设置正确,我将用户重定向到用户索引页面

return RedirectToAction("Index", "Users");
                    case "User":

在用户控制器上,我正在检查该用户是否为管理员,但会话变量 SessionWrapper.currentRequest 为空

if (SessionWrapper.currentRequest.Role == "Admin")
{
  users = db.UserRepository.GetAll();
}

我在这里做错了什么?

【问题讨论】:

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


    【解决方案1】:

    我发现了问题。我的 global.asax 文件中没有 Session_Start 和 Session_End 方法。我添加了这两个方法签名,这不再是问题。

    protected void Session_Start(object sender, EventArgs e)
    {
    
    }
    protected void Session_End(object sender, EventArgs e)
    {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 2016-05-12
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2014-02-16
      • 2018-08-22
      • 2020-04-12
      • 1970-01-01
      相关资源
      最近更新 更多