从foreach循环返回一个变量ASP.NET Core 5.0



我试图从foreach循环返回一个密码来进行一些验证,但我无法返回密码变量。我总是犯错误。我在控制器中执行此操作。

我的代码:

[HttpPost]
public IActionResult Login(userModel user)
{
ViewBag.Password = pwd.GetPassword(user);
string password = "";
foreach(var pwdR in ViewBag.Password.Rows)
{
password = pwdR[1];
}
return password; // Here I get this error: CS0029: Cannot implicitly convert type 'string' to 'Microsoft.AspNetCore.Mvc.IActionResult'
// VALIDATION CODE
....................
}

我做错了什么?

谢谢!

更新:

[HttpPost]
public IActionResult Login(userModel user)
{
ScryptEncoder enc = new ScryptEncoder();
UserModel pwd = new UserModel();
ViewBag.Password = pwd.GetPassword(user);
string password = "";
foreach(var pwdR in ViewBag.Password.Rows)
{
password = pwdR[1];
}
return password; // Here I get this error: CS0029: Cannot implicitly convert type 'string' to 'Microsoft.AspNetCore.Mvc.IActionResult'
// VALIDATION CODE
bool match = enc.Compare(user.pwd, password);
if (match) 
{
ViewBag.Error = "You are now logged in.";
return View();
} else
{
ViewBag.Error = "Login failed.";
return View();
}
}

加载所有用户并找到所需用户是一个很大的性能错误。

试试这个代码

[HttpPost]
public IActionResult Login(UserModel user)
{
ScryptEncoder enc = new ScryptEncoder();
var userNamePassword= GetUserNamePassword (user) ;
if(  userNamePassword==null)
ViewBag.Error = "Login failed. User is not found";
return View();
}
// VALIDATION CODE
bool match = enc.Compare(userNamePassword.Password, password);
if (match) 
{
ViewBag.Error = "You are now logged in.";
return View();
} else
{
ViewBag.Error = "Login failed.";
return View();
}
}

将您的模型类更改为该

public class UserNamePasswordModel
{
public string Username { get; set; }
public string Password { get; set; }
} 

并将此代码放置在登录操作附近的某个位置

private  UserNamePasswordModel GetUserNamePassword (UserModel user)
{
UserNamePasswordModel  userNamePassword= null;
var connectionString = "Server=localhost;Database=xxxx; uid = xxxx;Password=xxxx;";

using   (var connection = new MySqlConnection(connectionString))
{
var command =  new MySqlCommand("SELECT UserName, Password  FROM User WHERE Username = @Username", connection);
command.Parameters.AddWithValue("@Username", user.Username);
connection.Open();
var reader = command.ExecuteReader();
if (reader.HasRows)
{
if reader.Read()
{
userNamePassword= new UserNamePasswordModel
{
Username=  reader.GetString(0),
Password =   reader.GetString(1)
};
}
}

reader.Close();
}
}
return userNamePassword;

}

尝试返回Ok,其中包含密码,类似于:return Ok(password);

最新更新