我对 ASP.Net MVC 比较陌生,现在尝试使用内置的用户登录功能。我可以在注册 View 中注册用户。如果我尝试使用创建的用户登录,这也有效。我被重定向到母版页。
但我无法获取当前用户的 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 之前我还需要做其他事情吗?
最佳答案
答案就在您的代码中。这会返回什么?
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 写入浏览器。此 cookie 必须在 User.Identity
具有所有此声明信息(包括 NameIdentifier
)后续请求之前写入。
关于c# - 在 Asp.Net MVC 5 中获取登录用户的用户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26739778/