加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在ASP.NET中限制每个用户只有一个会话

发布时间:2020-12-15 06:49:10 所属栏目:百科 来源:网络整理
导读:是否有任何检测用户登录时是否已经有另一个会话使用相同的用户名,并阻止他再次登录或向他发送消息? 解决方法 您可以随时在global.asax中实现事件. 实现Application_Start()来设置System.Collections.Dictionary(或根据您的偏好),并将其存储在Application []
是否有任何检测用户登录时是否已经有另一个会话使用相同的用户名,并阻止他再次登录或向他发送消息?

解决方法

您可以随时在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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读