成功SignIn后User.Identity.GetUserId()返回null

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
string userId = User.Identity.GetUserId(); // 此时得到的值为null
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}

因为在调用SignInManager.PasswordSignInAsync(…)时不会影响当前request context的值,故此时使用User.Identity.GetUserId()返回的值为null。

解决办法:string userId = SignInManager.AuthenticationManager.AuthenticationResponseGrant.Identity.GetUserId(); 可获取到刚登录用户的ID。

 

点赞