Check if user is already logged in asp.net website

后端 未结 6 1581
不思量自难忘°
不思量自难忘° 2021-01-25 20:32

I am developing a website where in user is required to login to the system to be able to use it. The current functionality is: When user enters username and password, a check is

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-25 21:02

    This is how I managed to do it with the help of link provided by @Satinder singh.

    Global.asax.cs

        protected void Application_Start(object sender, EventArgs e)
        {
            Application["UsersLoggedIn"] = new System.Collections.Generic.List();
        }
    
        protected 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 d = Application["UsersLoggedIn"]
                    as System.Collections.Generic.List;
                if (d != null)
                {
                    lock (d)
                    {
                        d.Remove(userLoggedIn);
                    }
                }
            }
        }
    

    Login.aspx.cs

    protected bool Login(string userId)
        {
            System.Collections.Generic.List d = Application["UsersLoggedIn"]
                as System.Collections.Generic.List;
            if (d != null)
            {
                lock (d)
                {
                    if (d.Contains(userId))
                    {
                        // User is already logged in!!!
                        string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"];
                        if (userLoggedIn == user_id)
                        {
                            Session["UserLoggedIn"] = user_id;
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        string userLoggedIn = Session["UserLoggedIn"] == null ? string.Empty : (string)Session["UserLoggedIn"];
    
                        if (userLoggedIn != user_id)
                        {
                            d.Add(userId);
                        }
                    }
                }
            }
            Session["UserLoggedIn"] = userId;
            return true;
        }
    

    With above code, I am allowing any user to be logged in at any time only once. I used session variable to check if the request is from same browser, if so, I am allowing him/her to login else throwing a message "You are already logged in from another system".

提交回复
热议问题