登录控件身份验证不能与用户定义的数据库一起工作

本文关键字:数据库 一起 工作 定义 用户 控件 身份验证 不能 登录 | 更新日期: 2023-09-27 18:08:28

我设置了一个登录控件在我的web应用程序上使用,有问题。我试图通过用户定义的sql数据库验证登录控件,但它显示了无效列名'密码'的错误。我几乎什么都试过了,但都不奏效。我不知道我错在哪里。如果有人能帮帮我。这是我的代码。

protected void login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    SqlConnection mycon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    SqlDataAdapter myadp = new SqlDataAdapter();
    myadp.SelectCommand = new SqlCommand();
    myadp.SelectCommand.Connection = mycon;
    mycon.Open();
    myadp.SelectCommand.CommandText = "select *from UserData where username=@uname and password=@pswd";
    myadp.SelectCommand.Parameters.AddWithValue("@uname",login1.UserName);
    myadp.SelectCommand.Parameters.AddWithValue("@pswd",login1.Password);
    SqlDataReader dr;
    dr = myadp.SelectCommand.ExecuteReader();
    if (dr.Read())
    {
        e.Authenticated = true;
        Session["username"] = login1.UserName;
        Response.Redirect("~/Home.aspx");
    }
    else
    {
        Response.Write("<Script>alert('Error')</Script>");
    }  
    mycon.Close();
}

登录控件身份验证不能与用户定义的数据库一起工作

对于你的第一个问题,正如评论所说,你的数据库中没有password字段
对于第二个问题:-你正在检查if(dr.Read),你应该检查if(dr.HasRows)。您不需要在会话中存储用户名。你可以像@chinz说的那样通过User.Identity.Name获得。同样在你的web.config

<system.web>
        <authentication mode="Forms">
                   <forms loginUrl="login.aspx" name="login" protection="All"/>
        </authentication>
        <authorization>
                <deny users="?"/>
       </authorization>
</system.web>

这将增加您的页面的安全性。有关正确的身份验证方法,请参阅msdn文档和此