首页 > 解决方案 > 如何在不使用会员资格的情况下显示当前在线用户列表

问题描述

我需要显示当前登录到网站的用户列表。目前它显示登录的用户数,但我想显示谁也登录了?

在线.aspx:

<div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="panel">
                    <div class="panel-heading">
                        <h3 class="panel-title">Online Users</h3>
                    </div>
                    <div class="panel-body">
                        <asp:GridView
                            ID="gvOnlineUsers"
                            runat="server"
                            AutoGenerateColumns="False"
                            GridLines="None"
                            CssClass="table table-bordered table-hover">
                            <Columns>
                                <asp:BoundField DataField="country_name" HeaderText="Country" SortExpression="country_name"></asp:BoundField>
                                <asp:BoundField DataField="userCount" HeaderText="Users" ReadOnly="True" SortExpression="userCount"></asp:BoundField>
                            </Columns>
                        </asp:GridView>
                    </div>
                </div>
            </div>
        </div>
    </div>

当用户登录时:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        txtUsername.Focus();
        GetAuthenticationInfo();

        if (!IsPostBack)
        {
            if (Request.Browser.Cookies)
            {
                /*Check if the cookies with name UM_LOGIN exists on user's machine.*/
                if (Request.Cookies["UM_LOGIN"] != null)
                {
                    string strQuery = "EXEC sp_um_getCredentials '" + Request.Cookies["UM_LOGIN"]["username"].ToString() + "','" + Request.Cookies["UM_LOGIN"]["password"].ToString() + "'";
                    DataSet ds = DataControl.GetDataSet(strQuery);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "LOCKED")
                        {
                            Toastr.ShowToast("Your account is locked due to invalid login attempts and will be unlocked after " + ds.Tables[0].Rows[0]["unlockTimeRemaining"].ToString() + " or else you may contact your administrator to unlock the account.", "Account Locked", Toastr.Type.Error);
                        }
                        else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "INVALID")
                        {
                            int intAttemptsLeft = 0;
                            intAttemptsLeft = maxLoginAttempts - int.Parse(ds.Tables[0].Rows[0]["failed_attempts"].ToString());
                            Toastr.ShowToast("Password is invalid. You are left with " + intAttemptsLeft + " more attempts.", "Error", Toastr.Type.Error);
                        }
                        else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "VALID")
                        {
                            loginStatus = 1;
                            Session["loginStatus"] = loginStatus;
                            Session["userId"] = ds.Tables[0].Rows[0]["user_id_pk"].ToString();
                            Session["firstName"] = ds.Tables[0].Rows[0]["first_name"].ToString();
                            Session["middleName"] = ds.Tables[0].Rows[0]["middle_name"].ToString();
                            Session["lastName"] = ds.Tables[0].Rows[0]["last_name"].ToString();
                            Session["userName"] = txtUsername.Text.Trim();
                            Session["password"] = txtPassword.Text.Trim();
                            Session["userRole"] = ds.Tables[0].Rows[0]["user_role"].ToString();

                            if (bool.Parse(ds.Tables[0].Rows[0]["user_status"].ToString()).Equals(true))
                            {
                                /*Store the log date and time*/
                                string strQueryLog = "EXEC sp_um_addLog " + Int32.Parse(Session["userId"].ToString());
                                DataControl.ExecuteNonQuery(strQueryLog);
                                Response.Redirect(ResolveUrl("default.aspx"), false);
                            }
                            else
                                Toastr.ShowToast("Your account is suspended", "", Toastr.Type.Error);
                        }
                    }
                    else
                    {
                        Toastr.ShowToast("Invalid Username or Password", "", Toastr.Type.Error);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}

public void GetAuthenticationInfo()
{
    try
    {
        string strQuery = "SELECT remember_me, forgot_password, throttle_auth, maximum_attempts, company_name FROM tbl_settings";
        ds = DataControl.GetDataSet(strQuery);
        if (ds.Tables[0].Rows.Count > 0)
        {
            if (bool.Parse(ds.Tables[0].Rows[0]["remember_me"].ToString()) == true)
            {
                divRememberMe.Visible = true;
                rememberMe = true;
            }
            else
            {
                divRememberMe.Visible = false;
                rememberMe = false;
            }
            if (bool.Parse(ds.Tables[0].Rows[0]["forgot_password"].ToString()) == true)
            {
                divForgotPassword.Visible = true;
                forgotPassword = true;
            }
            else
            {
                divForgotPassword.Visible = false;
                forgotPassword = false;
            }
            maxLoginAttempts = Int32.Parse(ds.Tables[0].Rows[0]["maximum_attempts"].ToString());
            Session["maxLoginAttempts"] = maxLoginAttempts;

            strCompanyName = ds.Tables[0].Rows[0]["company_name"].ToString();
            Session["companyName"] = strCompanyName;
            lblCompanyName.Text = strCompanyName;
        }
        else
        {
            //
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}

protected void btnLogin_Click(object sender, EventArgs e)
{
    try
    {
        if (cbRememberMe.Checked && rememberMe == true)
        {
            if (Request.Browser.Cookies)
            {
                Response.Cookies["UM_LOGIN"].Expires = DateTime.Now.AddDays(360);
                Response.Cookies["UM_LOGIN"]["username"] = txtUsername.Text.Trim();
                Response.Cookies["UM_LOGIN"]["password"] = txtPassword.Text.Trim();
            }
            else
            {
                Response.Cookies["UM_LOGIN"]["username"] = txtUsername.Text.Trim();
                Response.Cookies["UM_LOGIN"]["password"] = txtPassword.Text.Trim();
            }
        }
        else
        {
            /*Clean the cookie UM_LOGIN.*/
            Response.Cookies["UM_LOGIN"].Expires = DateTime.Now.AddDays(-1);
        }
        string strQuery = "EXEC sp_um_getCredentials '" + txtUsername.Text.Trim() + "','" + txtPassword.Text.Trim() + "'";
        DataSet ds = DataControl.GetDataSet(strQuery);
        if (ds.Tables[0].Rows.Count > 0)
        {
            /*Check whether the user account is locked or unlocked due to invalid login attempts OR valid OR invalid.*/
            if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "LOCKED")
            {
                Toastr.ShowToast("Your accounts is locked due to invalid login attempts and will be unlocked after " + ds.Tables[0].Rows[0]["unlockTimeRemaining"].ToString() + " or else you may contact your administrator to unlock the account.", "Account Locked", Toastr.Type.Error);
            }
            else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "INVALID")
            {
                int intAttemptsLeft = 0;
                intAttemptsLeft = maxLoginAttempts - int.Parse(ds.Tables[0].Rows[0]["failed_attempts"].ToString());
                Toastr.ShowToast("Password is invalid. You are left with " + intAttemptsLeft + " more attempts.", "Error", Toastr.Type.Error);
            }
            else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "VALID")
            {
                loginStatus = 1;
                Session["loginStatus"] = loginStatus;
                Session["userId"] = ds.Tables[0].Rows[0]["user_id_pk"].ToString();
                Session["firstName"] = ds.Tables[0].Rows[0]["first_name"].ToString();
                Session["middleName"] = ds.Tables[0].Rows[0]["middle_name"].ToString();
                Session["lastName"] = ds.Tables[0].Rows[0]["last_name"].ToString();
                Session["userName"] = txtUsername.Text.Trim();
                Session["password"] = txtPassword.Text.Trim();
                Session["userRole"] = ds.Tables[0].Rows[0]["user_role"].ToString();

                /*Check whether the user is active or not.*/
                if (bool.Parse(ds.Tables[0].Rows[0]["user_status"].ToString()) == true)
                {
                    string strQueryLog = "EXEC sp_um_addLog " + Int32.Parse(Session["userId"].ToString());
                    DataControl.ExecuteNonQuery(strQueryLog);
                    Response.Redirect(ResolveUrl("default.aspx"), false);
                }
                else
                {
                    Toastr.ShowToast("Your account is inactive, contact your administrator to activate the account.", "Account Suspended", Toastr.Type.Error);
                }
            }
        }
        else
        {
            Toastr.ShowToast("Invalid username or password.", "", Toastr.Type.Error);
        }
    }

    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}

然后在我的Global.asax 中:

void Application_Start(object sender, EventArgs e) 
{
    Application["OnlineUsers"] = 0;
}

void Session_Start(object sender, EventArgs e) 
{
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
    Application.UnLock();
    Session.Timeout = 8;
}

void Session_End(object sender, EventArgs e) 
{
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
    Application.UnLock();
}    

所以基本上我想显示当前登录的用户Gridview

更新

代码背后

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        if (Session["userRole"] != null || Session["userRole"].ToString() != "")
        {
            if (Session["userRole"].ToString().Equals("Admin"))
            {
                getOnlineUsers();
            }
            else
            {
                Response.Redirect(ResolveUrl("~/eh/401.aspx"), false);
            }
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
}
public void getOnlineUsers()
{
    try
    {
        string strQuery = "SELECT * FROM tbl_um_user WHERE user_id_pk = '" + Session["userId"].ToString() + "'";
        ds = DataControl.GetDataSet(strQuery);
        if (ds.Tables[0].Rows.Count > 0)
        {
            gvOnlineUsers.DataSource = ds;
            gvOnlineUsers.DataBind();

            gvOnlineUsers.UseAccessibleHeader = true;
            gvOnlineUsers.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
        else
        {
            ds.Dispose();
            gvOnlineUsers.DataSource = ds;
            gvOnlineUsers.DataBind();
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally
    {
        //ds.Dispose();
    }
}

标签: c#asp.net

解决方案


推荐阅读