Search code examples
asp.net-mvcasp.net-mvc-5asp.net-identity

No user data available after calling SingInManager and returning a success MVC5


I am getting a NullReferenceException when I try to access the User data after a successful login. The inquiry here is about when the user data is actually available to be queried against in the sign in process. Here is the code that I have placed into the Login method of the Account controller:

  [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                var sh = new SoapHelper();
                var user = UserManager.FindById(User.Identity.GetUserId());
                Session["UserExists"] = true;
                Session["StartDate"] = DateTime.Now.ToString("yyyyMMdd");
                Session["EndDate"] = DateTime.Now.ToString("yyyyMMdd");
                Session["UserCompany"] = user.CompanyID;

The final line of code is where the error is thrown, am I not able to access the UserManager to get the data I need from the User table at this time in the login process?

Any help will be greatly appreciated!


Solution

  • After some more research and testing I found that the reason why you can't use User.Identity.Name in the same call with SignInManager.PasswordSignInAsync is that User.Identity filled out with the claims from authentication cookie (which are not parsed yet).

    So I tried a second call with an await to the UserManager

    var user = await UserManager.FindAsync(model.Email, model.Password);
    

    and it worked like a charm.