我是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());
}
在获取用户ID之前,我还需要做其他事情吗?
答案就在您的代码中。这会返回什么?
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 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句