I need to create a class that contains logic for checking a SQL Server table for user via Login control. When I run my code and enter data in Login control it does not recognize user and writes a error message. Can someone look my code for errors?
Here is the class code :
public int checkUser (string Username, string Password)
{
using (SqlConnection sqlCnn = new SqlConnection(cnn))
{
Int32 count = 0;
string sqlQuery = "SELECT COUNT(*) AS LoginInfo FROM users" +
"WHERE Username = @Name AND Password = @Password";
//sqlCnn.Open();
using (SqlCommand comm = new SqlCommand(sqlQuery, sqlCnn))
{
//comm.Parameters.AddWithValue("@Name", Username);
//comm.Parameters.AddWithValue("@Password", Password);
comm.Parameters.Add("@Name", SqlDbType.NChar).Value = Username;
comm.Parameters.Add("@Password", SqlDbType.NChar).Value = Password;
try
{
sqlCnn.Open();
count = (Int32)comm.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
finally
{
sqlCnn.Close();
}
return (Int32)count;
}
}
}
And this is the implementation code :
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
User1 user = new User1();
string name = Login1.UserName;
string pass = Login1.Password;
if (user.checkUser(name, pass) > 0)
{
Response.Redirect("mainPage.aspx");
}
else
{
Label1.Text = "Error";
}
}
Your query string should come out wrong as:
SELECT COUNT(*) AS LoginInfo FROM usersWHERE Username = @Name AND Password = @Password
And this is probably what is causing the exception.
I always use a verbatim string literal so that it's easier to copy the query, and you don't have to think about ending or starting each string with a space:
string sqlQuery = @"SELECT COUNT(*) AS LoginInfo FROM users
WHERE Username = @Name AND Password = @Password";
Instead of just Console.WriteLine("Error"); you should probably write the exception:
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace); //probably a good idea
}
You could also look into the InnerException if it's not null.
I see that you have big letters in your variables Username and Password . You should change the first character to be lowercase. I also always use the AddWithValue
comm.Parameters.AddWithValue("@Name", username);
Okay i found the solution for the problem. First mistake was in sql query. I shouldn't have forwarded data that the class accepts as values ( Username = @Name ==> name = @Name ). Second, in the implementation code there had to be added another line for the redirect to be able to transfer the approved user to another page:
FormsAuthentication.RedirectFromLoginPage(name, true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.