对ASP.NET成员身份使用SQL成员身份提供程序。我使用first.last作为用户名,它是根据表单上填写的用户详细信息以编程方式创建的
当用户提交表单时,我希望能够检查用户名是否存在,如果存在,则将其更改为用户名1,检查用户名1是否存在,并使其成为用户名2(如果存在),等等,直到它成为唯一的用户名。
我不知道如何执行存储过程,所以我尝试使用SQLDataReader来检查用户名是否存在。
问题出在我的循环上。逻辑基本上是设置一个布尔值,并保持循环并向计数器添加1,直到它找不到重复值。我已经经历过很多次了,即使它将布尔值设置为false,它也会不断循环。
有什么想法吗?
代码背后:
protected void Membership_add()
{
SqlConnection con = new SqlConnection(connectionString);
string NewUserNameString = FirstName.Text + "." + LastName.Text;
//Check for duplicate aspnet membership name and add a counter to it if exists
// Check for valid open database connection before query database
bool match = true;
SqlDataReader _SqlDataReader = null;
string TestNameString = NewUserNameString;
string selectDupeString = "SELECT UserId FROM aspnet_Users WHERE UserName = '" + TestNameString + "'";
SqlCommand SQLdatareaderCmd = new SqlCommand(selectDupeString, con);
int UserNameCounter = 0;
con.Open();
while (match = true)
{
//Open the connection
try
{
//Read the table
_SqlDataReader = SQLdatareaderCmd.ExecuteReader();
}
catch (Exception ex)
{
lblDatareaderEx.Text = "An Exception occurred. " + ex.Message + " " + ex.GetType().ToString();
}
if (_SqlDataReader.HasRows)
{
//match = true;
//increase counter by 1 for each record found and change First.Name to First.Namex
TestNameString = NewUserNameString;
UserNameCounter = UserNameCounter + 1;
TestNameString = TestNameString + UserNameCounter.ToString();
_SqlDataReader.Close();
_SqlDataReader.Dispose();
selectDupeString = "SELECT UserId FROM aspnet_Users WHERE UserName = '" + TestNameString + "'";
SQLdatareaderCmd = new SqlCommand(selectDupeString, con);
}
else
{
// close sql reader
_SqlDataReader.Close();
_SqlDataReader.Dispose();
//get out of loop
match = false;
}
}
con.Close();
con.Dispose();
}
此行:
while (match = true)
做作业
如果你想让你的代码工作,你必须做一个比较:
while (match == true)
或者,由于您的变量已经是bool,您可以直接使用该变量:
while(match)
目前您正在设置match
,而不是比较它的值。
尝试将while (match = true)
设置为while (match == true)
如果将代码分解成更小的块,代码会变得更简单、更容易阅读。
private string MembershipAddUser(string firstName, string lastName)
{
string username = firstName + "." + lastName;
int i = 0;
while (UserExists(username))
{
i++;
username = firstName + "." + lastName + i.ToString();
}
return username;
}
private bool UserExists(string username)
{
string sql = "SELECT COUNT(*) FROM dbo.aspnet_Users WHERE UserName = @UserName";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@UserName", username);
using (connection)
{
connection.Open();
int count = (int) command.ExecuteScalar();
return (count != 0);
}
}