Asp.net Identity : User.Identity.GetUserId() is always null and User.Identity.IsAuthenticated is alway false

守給你的承諾、 提交于 2019-11-27 17:53:32

问题


See my code below:

var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
    case SignInStatus.Success:
        string UserId = User.Identity.GetUserId(); 
        return RedirectToAction("ClientDetails","Home");
    case SignInStatus.LockedOut:
        return View("Lockout");
    case SignInStatus.RequiresVerification:
        return RedirectToAction("SendCode", "Account", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
    case SignInStatus.Failure:
    default:
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
}

The UserId is always null and User.Identity.IsAuthenticated is always false. But I can view the View ClientDetails which requires authentication.


回答1:


I assume your example is the code from your AccountController.Login() method. I had the same problem as you but discovered that the User object won't be populated until the next request. Try this approach:

case SignInStatus.Success:
    return RedirectToAction("DoWork", "Account");


public async Task<ActionResult> DoWork()
{
    //this works
    string UserId = User.Identity.GetUserId();
    //return to View or Redirect again
}



回答2:


For the "The UserId is always null" part of the question, you can look up the user by the model.UserName:

var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
    case SignInStatus.Success:
        ApplicationUser user = UserManager.FindByName(model.UserName);
        string UserId = user.Id;
        // UserId is now populated
        return RedirectToAction("ClientDetails","Home");

etc. Not sure if you wanted User.Identity.IsAuthenticated true or whether that was an observation - this doesn't change that part.




回答3:


Worked with me after tagging the method with [Authorize] attribute and sending the access-token in the authorize header, it seems that the access-token is needed to recognize the user



来源:https://stackoverflow.com/questions/25439275/asp-net-identity-user-identity-getuserid-is-always-null-and-user-identity-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!