Monday, June 22, 2015

Get All Logged in Users Asp.net MVC

[HttpPost]

        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (HttpRuntime.Cache["LoggedInUsers"] != null) //if the list exists, add this user to it
                    {
                        //get the list of logged in users from the cache
                        List loggedInUsers = (List)HttpRuntime.Cache["LoggedInUsers"];
                        //add this user to the list
                        loggedInUsers.Add(model.UserName);
                        //add the list back into the cache
                        HttpRuntime.Cache["LoggedInUsers"] = loggedInUsers;
                    }
                    else //the list does not exist so create it
                    {
                        //create a new list
                        List loggedInUsers = new List();
                        //add this user to the list
                        loggedInUsers.Add(model.UserName);
                        //add the list into the cache
                        HttpRuntime.Cache["LoggedInUsers"] = loggedInUsers;
                    }
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult LogOff()
        {

            string username = User.Identity.Name; //get the users username who is logged in

            if (HttpRuntime.Cache["LoggedInUsers"] != null)//check if the list has been created
            {
                //the list is not null so we retrieve it from the cache
                List loggedInUsers = (List)HttpRuntime.Cache["LoggedInUsers"];
                if (loggedInUsers.Contains(username))//if the user is in the list
                {
                    //then remove them
                    loggedInUsers.Remove(username);
                }
                // else do nothing

            }