-2

I'm setting up a project in C# ASP.NET MVC5 and I'm trying to give an error when you're entering incorrect username and password. So far I have tried with HandleError attribute without luck and now I'm trying with 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();
            }
        }
Zagros
  • 142
  • 2
  • 10

1 Answers1

2

.Single() throws an Exception if the sequence is empty, which will be the case for you if the email and password provided don't have a match. From 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() will return a null in your case if the sequence is empty, letting you proceed to the null check on the next line. From the other docs:

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

So try:

var usr = db.Users.SingleOrDefault(u => u.Email == user.Email && u.Password == user.Password);
Community
  • 1
  • 1
Broots Waymb
  • 4,713
  • 3
  • 28
  • 51
  • Thank you sir. This worked but could you please tell me how I can throw a proper error instead of displaying where the error in the code is? If you know what I mean... btw why did my help/question get devoted did I do something wrong? – Zagros Nov 12 '19 at 22:00
  • 1
    @Zagros - I haven't tried it (and I'm actually not all that familiar with MVC) but you could try something like this: https://stackoverflow.com/questions/13905164/how-to-make-custom-error-pages-work-in-asp-net-mvc-4 – Broots Waymb Nov 12 '19 at 22:02
  • Thanks for your help buddy, – Zagros Nov 12 '19 at 22:03