2013-10-30 55 views
2

我想实现一个代码,每个用户只能启用一个会话。 我使用窗体身份验证的asp.net。如何只允许每个用户一个活动会话

我看到这篇文章: Limit only one session per user in ASP.NET

,但我想反其道而行之,断开所有以前的会议。

这里是我的代码:

void Application_Start(object sender, EventArgs e) 
{ 
    Application["UsersLoggedIn"] = new System.Collections.Generic.Dictionary<string, string>(); } 

在用户登录时,我插入一条记录:用户名,会话ID。 如果用户名存在,我刚更新的SessionID

void Application_BeginRequest(object sender, EventArgs e) 
    { 
     System.Collections.Generic.Dictionary<string, string> d = HttpContext.Current.Application["UsersLoggedIn"] as System.Collections.Generic.Dictionary<string, string>; 
     if (d != null) 
     { 
      if (d.Count > 0) 
      { 
        string userName = HttpContext.Current.User.Identity.Name; 
        if (!string.IsNullOrEmpty(userName)) 
        { 
         if (d.ContainsKey(userName)) 
         { 
          if (d[userName] != HttpContext.Current.Session.SessionID) 
          { 
           FormsAuthentication.SignOut(); 
           Session.Abandon(); 
          } 
         } 
        } 
} 
} 

,但我得到空HttpContext.Current.User。 我也尝试了“AuthenticatedRequest”,但后来我得到了空Session。

有什么想法吗?

回答

2

如果要访问HttpContext.Current.User和Session,则应使用AcquireRequestState事件。

+0

谢谢!正是我所期待的。 – Inbal

2

如果您在负载平衡的情况下需要多个服务器,您需要以某种方式坚持这一点,但问题出现在您需要释放用户锁定时(无论是终止用户会话还是注销)。

相关问题