c# - ASP.NET MVC - 登录成功,但 userId 返回 null

标签 c# asp.net-mvc asp.net-mvc-5 asp.net-identity identity

我正在使用基本的 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/

相关文章:

c# - 如何使用 LINQ C# 过滤列表

c# - 模拟函数返回其输入时出现 TargetParameterCountException

asp.net-mvc - 结构图搜索每个页面的脚本 Controller

c# - 映射自定义路由 ASP.NET MVC5

c# - Azure AD Multi-Tenancy 权限

c# - 何时在我的 ASP.Net MVC 5 razor 语法 View 中使用@using

c# - 迭代非方(某种)矩阵

c# - 自动映射器创建新实例而不是映射属性

asp.net-mvc - 更改 SelectList 的内容

asp.net - 使用 jquery.load 将对象数组传递给 MVC 3