每当我用正确的数据检查我的数据库时,数据库都会将其作为错误的用户名返回,我不确定它是我的代码,还是我的数据库,她是代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=TOSHIBA0007\\TESTSERVER;Initial Catalog=users;Integrated Security=True");
conn.Open();
string checkuser = "select count(*) from userdatabase where Username=' " + Username.Text + " ' ";
SqlCommand UserComm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(UserComm.ExecuteScalar().ToString().Replace(" ", ""));
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = "select Password from userdatabase where Username=' "+Username.Text+" ' ";
SqlCommand passCom = new SqlCommand(checkPasswordQuery, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ", "");
if(password == Password.Text)
{
Session["New"] = Username.Text;
Response.Write("Password Accepted");
}
else
{
Response.Write("Password Incorrect");
}
}
else
{
Response.Write("Username is Incorrect");
}
}
}
任何和所有的帮助将不胜感激,因为我难以理解为什么这不起作用。
答案 0 :(得分:1)
问题:您在查询中的用户名之前和之后都有空格。
1.替换这个:
string checkuser = "select count(*) from userdatabase where Username=' " + Username.Text + " ' ";
有了这个:
string checkuser = "select count(*) from userdatabase where Username='" + Username.Text + "'";
2.替换这个:
string checkPasswordQuery = "select Password from userdatabase where Username=' "+Username.Text+" ' ";
有了这个:
string checkPasswordQuery = "select Password from userdatabase where Username='"+Username.Text+"'";
建议:1 您的查询对sql injection attacks
开放,因此我建议您使用parameterised queries
来避免这些问题。
建议2:您无需对用户名和密码进行多次比较。 您可以编写如下的单个查询来查找有效用户:
select count(*) from userdatabase where Username=@username and Password=@password;
解决方案:使用Parameterised Queries
进行单一查询
protected void Button_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=TOSHIBA0007\\TESTSERVER;Initial Catalog=users;Integrated Security=True");
conn.Open();
string checkuser = "select count(*) from userdatabase where Username=@username and Password=@password";
SqlCommand UserComm = new SqlCommand(checkuser, conn);
UserComm.Parameters.AddWithValue("@username",Username.Text);
UserComm.Parameters.AddWithValue("@password",Password.Text);
int temp = Convert.ToInt32(UserComm.ExecuteScalar());
conn.Close();
if (temp == 1)
{
Session["New"] = Username.Text;
Response.Write("User Is Valid!");
}
else
{
Response.Write("Invalid User Credentials!");
}
}
建议3:您不应将密码作为纯文本存储在数据库中,请注意这一点。有关如何以安全方式存储密码的详细信息,请参阅this link。