c# - 在 Asp.Net MVC 5 中获取登录用户的用户 ID

标签 c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity

我对 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/

相关文章:

c# - 使用 ServiceStack 存储和比较多个密码

c# - 在 SQLite 中为 WinRT 实现自定义排序规则

asp.net - Session_End 可以在窗口关闭时触发吗? (ASP.NET)

c# - 如何使用 structuremap asp.net mvc 注册可选装饰器或带有可选参数的装饰器?

c# - 具有过滤 dbContext 的 Multi-Tenancy Web 应用程序

c# - ldloc 还是 ldloca?

c# - 当属性抛出错误时,如何将其设置为空值?

c# - IIS 8.0 HTTP 错误 404.17 - 未找到请求的内容似乎是脚本,不会由静态文件处理程序提供服务

asp.net - 一个 ASP.Net 页面中存在多个 reCAPTCHA

asp.net-mvc - 创建 razor 自定义 View 引擎后 _ViewStart 停止工作