获取Asp.Net MVC 5中登录用户的UserID

Phi*_*ger 41 c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity

我是ASP.Net MVC的新手,现在尝试使用内置的用户登录功能.我可以在注册视图中注册用户.如果我尝试使用创建的用户登录,这也有效.我被重定向到母版页.

但是我无法获得当前用户的UserID.我在HomeController和AccountController中尝试了我的代码,但两者都没有用.第一行中的语句返回null.

var userID = User.Identity.GetUserId();

if (!string.IsNullOrEmpty(userID))
{
    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
    var currentUser = manager.FindById(User.Identity.GetUserId());
}
Run Code Online (Sandbox Code Playgroud)

在获取UserID之前,我是否需要做其他事情?

dan*_*wig 54

答案就在您的代码中.这又回来了什么?

var userID = User.Identity.GetUserId();
Run Code Online (Sandbox Code Playgroud)

如果你正在使用ASP.NET身份,然后登录(和重定向到另一页),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;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码块并不完全,但基本上是IIdentity.GetUserId扩展方法的作用.

如果这些都不起作用,那么用户可能还没有真正登录到您的站点.登录后,您必须在服务器将身份验证cookie写入浏览器之前重定向到另一个页面.必须在User.Identity拥有所有此类声明信息(包括NameIdentifier)后续请求之前编写此cookie .

  • 如果`User.Identity.GetUserId()`返回null,则意味着用户*未登录.请确保您调用此操作的任何操作都使用`[Authorize]`进行修饰,以强制仅登录用户可以得到它.未登录的任何人都将自动发送到您的登录页面. (2认同)
  • @ChrisPratt我遇到了同样的问题.GetUserId()始终返回null.我在我的控制器上有[授权],并且在我的请求下传递了持票人令牌.有任何想法吗? (2认同)