在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>   

解决方法

无论如何,是否可以检测到用户登录时是否已有另一个具有相同用户名的会话,并阻止他再次登录或向他发送消息?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...