我正在使用基本的 mvc-5 登录方法,并尝试在成功时访问用户 ID
[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();
returnUrl = CheckUserRoleAndRedirect();
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);
}
}
这里 string userId = User.Identity.GetUserId();
userId 第一次返回 null 但下次它工作正常
最佳答案
登录后(并重定向到另一个页面),IPrincipal.IIdentity
应该是 ClaimsIdentity
。你可以试试这个:
var claimsIdentity = User.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
// the principal identity is a claims identity.
// now we need to find the NameIdentifier claim
var userIdClaim = claimsIdentity.Claims
.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
if (userIdClaim != null)
{
var userIdValue = userIdClaim.Value;
}
}
这应该适合您。如果您仍然无法获取 id,那么您必须在服务器将身份验证 cookie 写入浏览器之前重定向到另一个页面。
或者另一种方法是:
switch (result)
{
case SignInStatus.Success:
ApplicationUser user = UserManager.FindByName(model.UserName);
string UserId = user.Id;
returnUrl = CheckUserRoleAndRedirect();
return RedirectToLocal(returnUrl);
}
关于c# - ASP.NET MVC - 登录成功,但 userId 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33343940/