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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
ViewState["LoginErrors"] = 0;
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (YourValidationFunction(Login1.UserName, Login1.Password))
{
// e.Authenticated = true;
Login1.Visible = false;
MessageLabel.Text = "Successfully Logged In";
}
else
{
e.Authenticated = false;
}
}
protected void Login1_LoginError(object sender, EventArgs e)
{
if (ViewState["LoginErrors"] == null)
ViewState["LoginErrors"] = 0;
int ErrorCount = (int)ViewState["LoginErrors"] + 1;
ViewState["LoginErrors"] = ErrorCount;
if ((ErrorCount > 3) && (Login1.PasswordRecoveryUrl != string.Empty))
Response.Redirect(Login1.PasswordRecoveryUrl);
}
private bool YourValidationFunction(string UserName, string Password)
{
bool boolReturnValue = false;
string strConnection = "server=example;database=TEST_dw;uid=test;pwd=test;";
SqlConnection sqlConnection = new SqlConnection(strConnection);
String SQLQuery = "SELECT UserName, Password FROM Login";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
SqlDataReader Dr;
sqlConnection.Open();
Dr = command.ExecuteReader();
while (Dr.Read())
{
if ((UserName == Dr["UserName"].ToString()) && (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
break;
}
Dr.Close();
return boolReturnValue;
}
}
}
代码运行时没有错误,但它没有验证用户名和密码,也成功登录错误的用户名和密码。 while循环和bool返回值解析时出错了
答案 0 :(得分:1)
您正在关闭while循环中的阅读器,并在boolReturnValue
的第一次迭代时返回值while
。这意味着如果if check
在循环的第一次迭代中不成立,它将始终返回false
。
// previous code
while (Dr.Read())
{
if ((UserName == Dr["UserName"].ToString()) && (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
break;
}
}
Dr.Close();
return boolReturnValue;
代码应如下所示。如果您使用Debug,您可以轻松地看到它。关于debuging的本教程对您有用:Tutorial
P.S对你来说更好的方法是查询数据库并查看是否有任何用户使用此密码和用户名,而不是每个用户,然后循环它们并检查是否。如果你有100000个用户,这将是性能问题,只是说 ......
private bool YourValidationFunction(string UserName, string Password)
{
string strConnection = "server=example;database=TEST_dw;uid=test;pwd=test;";
SqlConnection sqlConnection = new SqlConnection(strConnection);
sqlConnection.Open();
String query = "SELECT Count(*) FROM Login WHERE UserName=@UserName AND Password=@Password";
SqlCommand command = new SqlCommand(query, sqlConnection);
command.Parameters.AddWithValue("@UserName", UserName);
command.Parameters.AddWithValue("@Password", Password);
int result = Convert.ToInt32(command.ExecuteScalar());
sqlConnection.Close();
return result != 0 ? true : false;
}
最后一行是tenacy运算符return result != 0 ? true : false;
。这意味着
if(result !=0)
return true;
else
return false;
我建议您将来在其他类中编写数据访问层:以下是我编写示例DataAccessLayer的示例问题:checking user name or user email already exists