输入错误的用户名和密码时如何报错

How to give error when entering incorrect username and password

我正在用 C# ASP.NET MVC5 设置一个项目,当您输入不正确的用户名和密码时,我试图给出一个错误。到目前为止,我已经尝试使用 HandleError 属性但没有成功,现在我正在尝试使用 Membership.ValidateUser.

public ActionResult Login(User user)
        {
            using (CarsDBEntities db = new CarsDBEntities())
            {
                var usr = db.Users.Single(u => u.Email == user.Email && u.Password == user.Password);
                if (usr != null)
                {
                    Session["UserId"] = usr.UserId.ToString();
                    Session["Email"] = usr.Email.ToString();
                    Session["FirstName"] = usr.FirstName.ToString();
                    Session["LastName"] = usr.LastName.ToString();
                    return RedirectToAction("LoggedIn");
                }
                if (!Membership.ValidateUser(usr.Email, usr.Password))
                {
                    ModelState.AddModelError(string.Empty, "The user name or password is incorrect");
                    return View(user);
                }
                return View();
            }
        }
如果序列为空,

.Single() 会抛出异常,如果提供的电子邮件和密码不匹配,就会出现这种情况。来自 the docs:

InvalidOperationException
No element satisfies the condition in predicate.

-or-

More than one element satisfies the condition in predicate.

-or-

The source sequence is empty.

如果序列为空,

.SingleOrDefault() 将 return 为 null,让您继续进行下一行的 null 检查。来自 the other docs:

Returns a single, specific element of a sequence, or a default value if that element is not found.

所以尝试:

var usr = db.Users.SingleOrDefault(u => u.Email == user.Email && u.Password == user.Password);