c# - 从 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;
}
推荐阅读
- c# - c# .net core TagBuilder 不显示标签部分
- time-series - 如何用 plotly 绘制一个 x 轴和两个 y 轴的线曲线?
- node.js - 反应本机身份验证中的安全网问题
- django - Django:+:'int'和'str'不支持的操作数类型
- tabs - zsh 自动补全显示太多,烦人
- jestjs - 如何使用 Jest 从另一个元素的输入测试一个元素的输出?
- reactjs - 对象作为 React 子对象无效(找到:带有键 {fullName} 的对象)
- linux - Kubernetes Pod 中的容器是否在不同的“挂载”命名空间中运行?
- laravel - 如何在 Laravel API 中将数据放入表中?
- mysql - MySQL - 一对多查询,结果在单独的列中