限制在ASP.NET每个用户只有一个会话 [英] Limit only one session per user in ASP.NET

查看:206
本文介绍了限制在ASP.NET每个用户只有一个会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正是有检测,当用户登录,如果已经有另一个会话使用相同的用户名,并再次登录阻止他或给他发邮件?

Is there anyway to detect when a user logins if there is already another session with the same username, and block him from logging in again or send him a message?

推荐答案

您可以始终贯彻在Global.asax中的事件。

You could always implement the events in global.asax.

实施的Application_Start()设置一个System.Collections.Dictionary(或你的preference),并存储在应用程序的[]集合,当用户logsin,添加用户名。从集合中删除Session_End中()。请记住,使用了锁的关键字,而与收集工作:)

Implement Application_Start() to setup a System.Collections.Dictionary (or at your preference) and store that in the Application[] collection, when a user logsin, add the username. Remove from the collection in Session_End(). Remember to use the 'lock' keyword while working with the collection :)

玩得开心!

例如:

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

这篇关于限制在ASP.NET每个用户只有一个会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆