我对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之前我是否需要做其他事情?
答案 0 :(得分:53)
答案就在您的代码中。这又回来了什么?
var userID = User.Identity.GetUserId();
如果您使用的是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;
}
}
上面的代码块并不完全,但基本上是IIdentity.GetUserId
扩展方法的作用。
如果这些都不起作用,那么用户可能还没有真正登录到您的网站。登录后,您必须在服务器将身份验证cookie写入浏览器之前重定向到另一个页面。必须在User.Identity
包含所有此类声明信息(包括后续请求中的NameIdentifier
) 之前写入此Cookie。