Search code examples
c#asp.net-mvcforms-authentication

HttpContext.User.Identity.IsAuthenticated throws System.NullReferenceException: Object reference not set to an instance of an object


My code is simple like :

[HttpGet]
public ActionResult Login ()
{
   if (User.Identity.IsAuthenticated)
   {
      return RedirectToAction("Index", "Home");
   }
   return View(new LoginModel());
}

[HttpPost]
public ActionReslt Login (LoginModel model)
{
    if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.Email, model.Password))
              {
                  FormsAuthentication.SetAuthCookie(model.Email, false);

                  return RedirectToAction("Index","Home");
              }
        }

    return View(model);
}

But my Log Service sometimes receive this error! System.NullReferenceException: Object reference not set to an instance of an object

I don't think that the best practice to do null checks for every reference like :

if (User!=null && User.Identity!=null && User.Identity.IsAuthenticated)

Could you tell me why sometimes it is null ? and sometimes not ? What is the best practice for it?


Solution

  • You should use Request.IsAuthenticated instead of User.Identity.IsAuthenticated

    Page.User.Identity.IsAuthenticated returns object reference not set to instance of object

    Internally Request.IsAuthenticated will verify that the User and it's Identity are set (not null). You could do the same in your code, but why bother.

    User.Identity.IsAuthenticated is set when you invoke these methods :

    FormsAuthentication.Authenticate(name, pwd)
    

    Or

    Membership.ValidateUser(name, pwd)
    

    Or other Authentication mechanism methods that set cookies