[英]Limit only one session per user in ASP.NET
无论如何检测用户何时登录是否已经有另一个具有相同用户名的会话,并阻止他再次登录或向他发送消息?
您始终可以在global.asax中实现事件。
实现Application_Start()以设置System.Collections.Dictionary(或根据您的喜好)并将其存储在Application []集合中,当用户登录时,添加用户名。 从Session_End()中的集合中删除。 在使用集合时,请记住使用'lock'关键字:)
玩得开心!
例:
[page.aspx]
public partial class page : System.Web.UI.Page {
protected bool Login(string userName) {
System.Collections.Generic.List<string> d = Application["UsersLoggedIn"]
as System.Collections.Generic.List<string>;
if (d != null) {
lock (d) {
if (d.Contains(userName)) {
// User is already logged in!!!
return false;
}
d.Add(userName);
}
}
Session["UserLoggedIn"] = userName;
return true;
}
protected void Logout() {
Session.Abandon();
}
}
[global.asax]
<%@ Application Language="C#" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e) {
Application["UsersLoggedIn"] = new System.Collections.Generic.List<string>();
}
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);
}
}
}
}
</script>
我已经实现了这一点,当用户登录时,它会在他们登录的数据库中设置一个标志。这是一个表示他们登录多少次的int。我们允许两个。 然后在验证用户时检查一下。
您可以通过使用Application对象跟踪用户登录的global.asax。
在Session_Start方法或登录方法中,您可以检查用户是否存储在Application对象中。
在Session_End方法或注销方法中,您需要从Application对象中删除用户。
如果您无法识别用户注销事件(他们可能会单击注销,关闭选项卡,关闭整个浏览器,或者可能只是关闭计算机......),请不要将其存储在数据库中。 使用会话来执行相同的检查。
您可以将用户的SessionID存储在数据库中。 在每次登录时,将唯一用户名和SessionID的组合存储到数据库中。 在母版页中,您将查询包含在数据库中,以检查当前使用的用户名的最后一次登录是否来自同一会话。 如果没有,请放弃会话并重定向到登录页面。
我发布的行为应该注销第二个用户。 您可以将Session.Abandon更改为您想要的行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.