登录过程使用实体框架asp.net mvc
本文关键字:asp net mvc 框架 实体 过程 登录 | 更新日期: 2023-09-27 18:29:57
我想在我的项目中进行登录密码验证。当用户点击登录按钮时,编译器会转到这个方法
public ActionResult VerifyPassword(User user)
{
var givenPassword =user.Password;
var givenUserName=user.UserName;
//now i need compare password
var myUser=db.User.Find(somevalue)//find user from database,
But how can i do this????Because somevalue needs to be a Primary Key
}
如果我做错了什么。请给我指正确的方向我在网上搜索了很多,但没有找到使用实体框架来实现这一点的教程。
您实际上不需要主键来匹配数据库中的用户。
您可以使用他们的用户名(应该是唯一的)在数据库中查找他们的记录。
试试这样的东西:
public ActionResult VerifyPassword(User user)
{
//The ".FirstOrDefault()" method will return either the first matched
//result or null
var myUser = db.Users
.FirstOrDefault(u => u.Username == user.Username
&& u.Password == user.Password);
if(myUser != null) //User was found
{
//Proceed with your login process...
}
else //User was not found
{
//Do something to let them know that their credentials were not valid
}
}
还可以考虑对模型验证进行一些研究,研究ModelState.IsValid
是一个很好的开始。
应该这样修改。。。
public ActionResult VerifyPassword(User user)
{
//The ".FirstOrDefault()" method will return either the first matched
//result or null
User myUser = dbContext.Users.FirstOrDefault
(u => u.Username.Equals(user.Username) && u.Password.Equals(user.Password));
if (myUser != null)
{
//User was found
//Proceed with your login process...
}
else //User was not found
{
//Do something to let them know that their credentials were not valid
}
}
public ActionResult Login(StudentLogin sl)
{
if (sl.Email != null)
{
if (ModelState.IsValid) // this is check validity
{
StudentEntities1 se = new StudentEntities1();
var v = se.StudentLogins.Where(a => a.Email.Equals(sl.Email) && a.Password.Equals(sl.Password)).FirstOrDefault();
if (v != null)
{
Session["LogedUserID"] = v.Id.ToString();
//Session["LogedUserFullname"] = v.FullName.ToString();
return RedirectToAction("Success", "Student");
}
}
return View(sl);
}
else
{
return View();
}
}
public ActionResult Login(Login_T l)
{
using (AppHREntities db = new AppHREntities())
{
var obj = db.Login_T.Where(a => a.UserName.Equals(l.UserName) && a.Password.Equals(l.Password) && l.Type.Equals("HR")).Count();
var obj1 = db.Login_T.Where(a => a.UserName.Equals(l.UserName) && a.Password.Equals(l.Password) && l.Type.Equals("USER")).Count();
if (obj > 0)
{
MessageBox.Show("SUCESSFULLY LOGGED IN.");
return RedirectToAction("../Home/HR_Dashboard");
}
else if(obj1 > 0)
{
MessageBox.Show("SUCESSFULLY LOGGED IN.");
return RedirectToAction("../Home/Emp_Dashboard");
}
else
{
MessageBox.Show("WRONG PASSWORD.");
return RedirectToAction("Index");
}
}
}