0

I would like to ask, why UserId is null (in code below) after user log in.

OR

I need redirect users depending on the they roles. I need make it As Simple As Possible.

// POST: /Account/Login
    [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:
                string UserId = User.Identity.GetUserId(); <------ HERE
                HelpRoles hr = new HelpRoles();
                returnUrl = hr.CheckUserRoleAndRedirect(UserId);
                return RedirectToLocal(returnUrl);

2 Answers2

4

The User object is set based on the decrypted cookies after the request is authenticated, and these cookies aren't set until the next request so the page needs to be refreshed before User.Identity is not null.

For more info, see this post.

To work around this, within the success case you can get the user from the DB using the email address and use the ID on that instead.

Community
  • 1
  • 1
John Mc
  • 2,862
  • 1
  • 22
  • 37
1

Like John Mc said to work around this you have to the get user in the Success case. So you might want something like this before getting UserId

var user = userManager.Find(model.UserName, model.Password);

or

var user = userManager.FindByEmail(model.Email);

or

var user = userManager.FindByName(model.Username);

EDIT

In this case you wouldn't have to use your method as shown below string UserId = User.Identity.GetUserId(); <------ HERE

because once you get the user object you can get the id field in it like user.Id

jamiedanq
  • 967
  • 7
  • 12