您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在ASP.NET中,每个用户只能限制一个会话

在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>   
dotnet 2022/1/1 18:28:54 有333人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶