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 .
| 归档时间: |
|
| 查看次数: |
67411 次 |
| 最近记录: |