-1
      public ActionResult LogIn()
    {
        return View();
    }
    [HttpPost]
    public ActionResult LogIn(UserLogins p, UserRecipe u)
    {
        ////var s = context.plate.FirstOrDefault( x => x.Email.Equals(p.Email) && x.Password.Equals(p.Password));
        var details = (from userlist in context.plate
                       where userlist.Email == p.Email && userlist.Password == p.Password
                       select new
                       {
                           userlist.UserID,
                           userlist.Name,
                           userlist.Email
                       });


        if (details != null)
        {
            //    Session["User"] = s;
            Session["User"] = p.Email;
            Session["Name"] = details.FirstOrDefault().Name;
            Session["UserId"] = details.FirstOrDefault().UserID;
            u.UserId = Convert.ToInt32(Session["UserId"]);
            context.SaveChanges();
            TempData["Added"] = "You are successfully Logged in";
            return RedirectToAction("ShowProducts");
        }

        else
        {
            TempData["Added"] = "Invalid Username or password";
            return RedirectToAction("LogIn");
        }
    }

this is my code i get a Null Reference Exception when i entered wrong data .It works fine when i entered correct data .Null Reference Exception is appeared on Session["UserId"].

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • Well yes, you're using `details.FirstOrDefault()`, which will return `null` if `details` is empty. So that'll be a null reference. `details` itself will never be null. – Jon Skeet Nov 19 '17 at 19:06
  • Whenever you face a `NullReferenceException`, you should find out what's null first - see https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it. Then you can address that. – Jon Skeet Nov 19 '17 at 19:06
  • Additionally, it looks like you're using an **incredibly insecure** password scheme, with the passwords stored as plain text. Please don't do that, even for a system you don't really care about - get into good habits early. – Jon Skeet Nov 19 '17 at 19:06
  • Session["UserId"]=details.FirstOrDefault().UserID;........this line is giving this error .....i know what null reference means if some variable dont have a value.... – sohail malik Nov 19 '17 at 19:07
  • Well no, it's if you try to dereference a null value. (Even in the case where it's dereferencing a variable, the variable has a value - it's a null reference.) So have you worked out what the null reference is here? (Hint: it's the return value for `details.FirstOrDefault()`. Have you read the docs for `FirstOrDefault()`?) How do you expect `details` to ever be null? – Jon Skeet Nov 19 '17 at 19:08
  • Looks like you have some kind of validator, and `Session["UserId"]` will be null when you input invalid input. Therefore, `Convert.ToInt32(Session["UserId"])` will throw null pointer exception. – realharry Nov 19 '17 at 19:09
  • @realharry: No, that would return 0. `Convert.ToInt32(null)` is well-defined to return null. The problem is deferencing the result of `FirstOrDefault()`. – Jon Skeet Nov 19 '17 at 19:10
  • actually if i dont enter details.FirstOrDefault() then it is giving me zero value thats why i select this statement – sohail malik Nov 19 '17 at 19:10
  • 1
    Use your commented out code instead and that will work. – CodingYoshi Nov 19 '17 at 19:14
  • "actually if i dont enter details.FirstOrDefault() then it is giving me zero value" - it's *really* unclear what you mean by that. – Jon Skeet Nov 19 '17 at 19:16
  • @JonSkeet You are right. `Convert.ToInt32(null)` doesn't throw an exception. (Its value is defined to be 0, actually.) But, the question/description does not make sense then. If `FirstOrDefault()` was null, the exception will be thrown the line before (`Session["Name"] = ...`) not in the line including `Session["UserId"]` as suggested. The only other reason why it can throw the npe is because `u` is null (in `u.UserId`). That would not make sense either because it's stated that the exception happens only when he inputs wrong data. – realharry Nov 19 '17 at 19:23
  • @realharry: I suspect the OP has just misdiagnosed the issue. It makes perfect sense for the error to be due to `FirstOrDefault()` returning null. – Jon Skeet Nov 19 '17 at 19:27
  • @JonSkeet On second thought, you are right. The most plausible answer is (based on OP's "inputting wrong data" reference), the `FirstOrDefault()` will return null when the query did not return any valid value. Hence NPE. That makes sense. – realharry Nov 19 '17 at 19:29
  • 1
    So far it looks like regular duplicate of "how to love NRE and maybe to fix it". If you have solid [MCVE] this indeed can be re-opened, but at very least you need to clarify why you believe that `u` in `u.UserId` should not be null when you pass no data. – Alexei Levenkov Nov 19 '17 at 19:31
  • @realharry there is a good chance that whatever maps input to `UserRecipe` eats up exception and return null... But in this case question should be very different and not related to NRE (like "why when input is ... my action argument is null" + solid [MCVE]) – Alexei Levenkov Nov 19 '17 at 19:35

2 Answers2

1

It seems it should give exception on the:

Session["Name"] = details.FirstOrDefault().Name;

Since if the collection is empty the method FirstOrDefault returns default(TSource), that in your case seems to be null since TSource is a class, you should check it before getting the Name property.

var user = details.FirstOrDefault();
if(user != null) {
    Session["User"] = p.Email;
    Session["Name"] = user.Name;
    Session["UserId"] = user.UserID;
}
Stefano Liboni
  • 149
  • 2
  • 11
  • it is giving me exception on Session["UserId"] = user.UserID; not on which you are pointing.....sorry for bad english – sohail malik Nov 19 '17 at 19:19
  • @sohailmalik: But is that after you've made the change? `Session["UserId"] = user.UserId` isn't in the code that you posted. – Jon Skeet Nov 19 '17 at 19:28
  • @JonSkeet sorry for that actually this line Session["UserId"] = details.FirstOrDefault().UserID; giving me exception – sohail malik Nov 19 '17 at 19:31
  • 1
    @sohailmalik: I suspect you're misdiagnosing that. Or `details.FirstOrDefault()` first returns a non-null value, then a null value, which is feasible but unlikely - running the query twice is a bad idea anyway. – Jon Skeet Nov 19 '17 at 19:32
  • I suggest to add some breakpoints or logs to check (1) if the execution enters the if(user != null) and also (2) the value of user – Stefano Liboni Nov 19 '17 at 19:33
  • @JonSkeet that's one of the reason I suggested to use a "user" variable – Stefano Liboni Nov 19 '17 at 19:36
  • @JonSkeet actually my whole code is based on details.FirstOrDefault() the code does not get the UserId and Name if i dont write this code and it is passing to other tables as well so i stuck here now. :( – sohail malik Nov 19 '17 at 19:36
  • @sohailmalik: Sorry, but you need to spend *much* more time on clearly communicating what you mean. It's fine to call `details.FirstOrDefault()`, but a) you should do so only once; b) you should check whether that returns null. Currently you're checking whether `details` is null, which it *never* will be. – Jon Skeet Nov 19 '17 at 19:40
  • @sohailmalik you can use the FirstOrDefault(), but just once setting the user variable with it's return value, not twice. And instead of checking if(details != null), check if(user != null). I think your debugger stops on the line after the exception has been thrown. Try it and if it gives exception make a screenshot – Stefano Liboni Nov 19 '17 at 19:41
0

You have the query below which will never be null. If nothing is found in the database, it will return empty list.

var details = (from userlist in context.plate
                   where userlist.Email == p.Email && userlist.Password == p.Password
                   select new
                   {
                       userlist.UserID,
                       userlist.Name,
                       userlist.Email
                   });

So when you check if details != null, it will return true because it is not null. However it is empty. Therefore, when you do this:

if (details != null)
{
    Session["Name"] = details.FirstOrDefault().Name;
}

Since details is empty, FirstOrDefault will return null so essentially you are doing this: null.Name and that is why you are getting a null reference exception.

Fix

Search the db for the target user, if not found, leave right away. If found do what you need to:

var target = context.plate.FirstOrDefault(x => x.Email == p.Email && x.Password == p.Password);
if (target == null)
{
    TempData["Added"] = "Invalid Username or password";
    return RedirectToAction("LogIn");
}

// success
Session["User"] = p.Email;
Session["Name"] = target.Name;
Session["UserId"] = target.UserID;
u.UserId = Convert.ToInt32(Session["UserId"]);
context.SaveChanges();
TempData["Added"] = "You are successfully Logged in";
return RedirectToAction("ShowProducts");
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64