在Asp.NetMVC 5中获取已登录用户的UserID

本文关键字:登录 用户 UserID 获取 Asp NetMVC | 更新日期: 2023-09-27 18:28:59

我对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());
}

在获取UserID之前,我是否必须访问其他内容?

在Asp.NetMVC 5中获取已登录用户的UserID

答案就在代码中。这会返回什么?

var userID = User.Identity.GetUserId();

如果您使用的是ASP.NET Identity,则登录(并重定向到另一个页面)后,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;
    }
}

上面的代码块并不完全是IIdentity.GetUserId扩展方法所做的,但本质上是这样的。

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