这就是我通过所提供的链接设法做到这一点的方法@Satinder singh
。
protected void Application_Start(object sender, EventArgs e)
{
Application["UsersLoggedIn"] = new System.Collections.Generic.List<string>();
}
protected void Session_End(object sender, EventArgs e)
{
// NOTE: you might want to call this from the .logout() method - aswell -, to speed things up
string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"];
if (userLoggedIn.Length > 0)
{
System.Collections.Generic.List<string> d = Application["UsersLoggedIn"]
as System.Collections.Generic.List<string>;
if (d != null)
{
lock (d)
{
d.Remove(userLoggedIn);
}
}
}
}
protected bool Login(string userId)
{
System.Collections.Generic.List<string> d = Application["UsersLoggedIn"]
as System.Collections.Generic.List<string>;
if (d != null)
{
lock (d)
{
if (d.Contains(userId))
{
// User is already logged in!!!
string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"];
if (userLoggedIn == user_id)
{
Session["UserLoggedIn"] = user_id;
return true;
}
else
{
return false;
}
}
else
{
string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"];
if (userLoggedIn != user_id)
{
d.Add(userId);
}
}
}
}
Session["UserLoggedIn"] = userId;
return true;
}
使用上面的代码,我允许任何用户在任何时间只能登录一次。我使用了会话变量来检查请求是否来自同一浏览器,如果是,我允许他/她登录,否则抛出一条消息“您已经从另一个系统登录”。