阻止登录已登录的用户

时间:2012-08-21 10:09:55

标签: c# asp.net session authentication

您好我想检查数据库是否已经登录用户如果他已登录停止登录这里是我的代码样本thx求助。

protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
    {
        String name = ((Login)LoginView1.FindControl("Login1")).UserName;
        SqlConnection source_db = new SqlConnection();
        source_db.ConnectionString = ConfigurationManager.ConnectionStrings["source"].ConnectionString;//konfiguracja polaczenia z web.cfg 
        SqlCommand sql_polecenie3 = new SqlCommand("select Status from  aspnet_Users where UserName='" + name + "';", source_db);
        try
        {
            source_db.Open();//otwiera polaczenie
            if ((int)sql_polecenie3.ExecuteScalar() == 1)
            {
                Label1.Visible = true;
            }
            else
            {
                Label1.Visible = false;
            }
            source_db.Close();//zamyka polaczenie
        }
        catch (Exception)
        {
            source_db.Close();//zamyka polaczenie
        }
    }

3 个答案:

答案 0 :(得分:2)

亚历克斯,我永远不会使用你的代码...你做了几件事情,最重要的是,任何人都可以从你刚刚展示的内容中删除你的整个数据库。

首先要做的事情 ......

  • 您应始终将数据库访问(数据库代码)放在另一个项目中(通常是 Library Project - DLL) - see my answer on this
  • 您应该始终处置您的对象,在您的情况下,您可以安全地使用using以及SqlConnection {/ 1}}中的SqlCommand关键字。
  • 除非您确定自己是sanitizing your input,否则应该始终使用sql变量并且不要直接通过附加代码创建SQL查询。

关于你的答案它自己,如果你添加e.Cancel = true;,这将告诉你你已经自定义了响应,并且你不希望对象继续进行自动响应。 / p>

答案 1 :(得分:1)

登录控件为此目的提供了一个事件Authenticate 如果您想进行一些自定义检查并在此基础上拒绝登录,则应使用authenticate事件。

<asp:Login id="Login1" runat="server"
                OnAuthenticate="OnAuthenticate">
            </asp:Login>



private void OnAuthenticate(object sender, AuthenticateEventArgs e)
{
    bool Authenticated = false;
    Authenticated = SiteSpecificAuthenticationMethod(Login1.UserName, Login1.Password);

    e.Authenticated = Authenticated;
}

答案 2 :(得分:0)

答案是添加e.Cancel = true或false取决于我们想取消登录时。