我在应用程序的后端创建了以下WebMethod
,用户通过前端登录。
[WebMethod]
public String Login(String userName, String password)
{
OleDbConnection connect = new OleDbConnection(connection);
connect.Open();
OleDbCommand command = new OleDbCommand("Select * from login where userName='" + userName + "' and password ='" + password + "'", connect);
command.CommandType = CommandType.Text;
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = command;
DataSet NSNSet = new DataSet();
adapter.Fill(NSNSet);
string username = NSNSet.Tables[0].Rows[0]["firstName"].ToString() + NSNSet.Tables[0].Rows[0]["lastName"].ToString();
int userID = System.Convert.ToInt16(NSNSet.Tables[0].Rows[0]["UID"].ToString());
return username + "," + userID;
}
目前,我已经在错误处理中指出了-
catch(Exception ex)
{
string error = System.Convert.ToString(ex);
if (error.Contains("There is no row at position 0"))
{
status.Text = "Incorrect Username/Password combination";
}
}
这可以正常工作,但是我该如何对我的代码进行错误处理,以使其返回更具体的错误,即指出
userName
或password
具体是否不正确?
最佳答案
您应该这样做:
public String Login(String userName, String password)
{
OleDbConnection connect = new OleDbConnection(connection);
connect.Open();
OleDbCommand command = new OleDbCommand("Select UID, firstName, lastName from login where userName=? and password =?", connect);
command.CommandType = CommandType.Text;
//to avoid sql injection
command.Parameters.Add(userName);
command.Parameters.Add(password);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = command;
DataSet NSNSet = new DataSet();
adapter.Fill(NSNSet);
if (NSNSet.Tables[0].Rows.Count == 0)
return "Access denied";
string username = NSNSet.Tables[0].Rows[0]["firstName"].ToString() + NSNSet.Tables[0].Rows[0]["lastName"].ToString();
int userID = int.Parse(NSNSet.Tables[0].Rows[0]["UID"].ToString());
return username + "," + userID;
}
或者,使用DataReader以获得更好的性能:
public String Login(String userName, String password)
{
OleDbConnection connect = new OleDbConnection(connection);
connect.Open();
OleDbCommand command = new OleDbCommand("Select UID, firstName, lastName from login where userName=? and password =?", connect);
command.CommandType = CommandType.Text;
//to avoid sql injection
command.Parameters.Add(userName);
command.Parameters.Add(password);
OleDbDataReader reader=command.ExecuteReader();
if (reader.Read())
{
//that means there's at least one row
string username = reader["firstName"] + " " + reader["lastName"];
int userID = int.Parse(reader["UID"].ToString());
return username + "," + userID;
}
else
{
//no combination username-password found
return "Access denied";
}
}
关于c# - 分割用户名和密码凭证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11260311/