7

我想在我的项目中进行登录密码验证。当用户单击登录按钮时,编译器会转到此方法

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

}

如果我做错了什么。请指出我正确的方向我在网上搜索了很多。但是没有找到使用实体框架来完成这个的教程。

4

3 回答 3

11

您实际上不需要主键来匹配数据库中的用户。

您可以使用他们的用户名(应该是唯一的)在数据库中找到他们的记录。

尝试这样的事情:

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是一个很好的开始。

于 2013-09-01T07:21:00.507 回答
0

应该这样修改...

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
            }
        }
于 2013-09-01T10:18:02.807 回答
0
    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();
        }
    }
于 2015-06-25T04:56:32.390 回答