我试图让人们使用他们的UserID(int)或他们的用户名(字符串)登录。我想这样做的方法是创建两个单独的方法,一个接受一个字符串,一个接受一个int。但我无法让这个工作,似乎可能有更好的解决方案。
public static string ForgotPassword ( string username )
{
using ( var conn = new SqlConnection( GetConnectionString() ) )
using ( var cmd = conn.CreateCommand() )
{
conn.Open();
cmd.CommandText =
@"SELECT
Password
FROM
Distributor
WHERE
Username = @username";
cmd.Parameters.AddWithValue( "@username", (string)username );
using ( var reader = cmd.ExecuteReader() )
{
if ( !reader.Read() )
{
// no results found
return null;
}
return reader.GetString( reader.GetOrdinal( "Password" ) );
}
}
}
public static string ForgotPassword ( int username )
{
using ( var conn = new SqlConnection( GetConnectionString() ) )
using ( var cmd = conn.CreateCommand() )
{
conn.Open();
cmd.CommandText =
@"SELECT
Password
FROM
Distributor
WHERE
DistributorID= @username";
cmd.Parameters.AddWithValue( "@username", (int)username );
using ( var reader = cmd.ExecuteReader() )
{
if ( !reader.Read() )
{
// no results found
return null;
}
return reader.GetString( reader.GetOrdinal( "Password" ) );
}
}
}
允许他们使用user_id或用户名登录的最佳方式是什么?
答案 0 :(得分:2)
在你的第一个方法中,我将从该用户名获取userId,然后将其传递给第二个方法。
如果用户名与UserID不匹配,则以与UserID不存在时相同的方式返回错误。
public static string ForgotPassword ( string username )
{
int userid = //Get userid from username
return ForgotPassword(userid);
}
public static string ForgotPassword ( int username )
{
using ( var conn = new SqlConnection( GetConnectionString() ) )
using ( var cmd = conn.CreateCommand() )
{
conn.Open();
cmd.CommandText =
@"SELECT
Password
FROM
Distributor
WHERE
DistributorID= @username";
cmd.Parameters.AddWithValue( "@username", (int)username );
using ( var reader = cmd.ExecuteReader() )
{
if ( !reader.Read() )
{
// no results found
return null;
}
return reader.GetString( reader.GetOrdinal( "Password" ) );
}
}
}