我正在使用dapper库创建一个登录表单这里有些错误我似乎无法使其工作,即使密码或用户名错误它会打开新表单
if (string.IsNullOrEmpty(txtUsername.Text))
{
MessageBox.Show("Please enter your usernmae.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtUsername.Focus();
return;
}
try
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
var data = db.Query("select Username,Password from UserLog", commandType: CommandType.Text);
if ((data.SingleOrDefault() !=null)
{
MessageBox.Show("You have been succesfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
FormHome frm= new FormHome();
frm.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Your Username or Password is Incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 0 :(得分:2)
您只是将此查询发送到数据库,因此无论登录信息如何,它都会每次都返回结果:
select Username, Password from UserLog
当然,由于您没有过滤记录,所以它会通过。只要您在数据库中有1条记录,它就会通过。
您需要发送用户登录信息并检查是否存在记录,其中包含您尝试进行身份验证的当前用户的登录信息:
IEnumerable users = db
.Query("select Username, Password from UserLog where UserName = @UserName and Password = @Password",
new {UserName = txtUsername.Text, Password = // put the password here});
if (users.Any())
{
// authenticated so do whatever
}