Get UserID of logged-in user in Asp.Net MVC 5

前端 未结 1 701
一生所求
一生所求 2020-12-01 05:30

I\'m relatively new to ASP.Net MVC and try to use the built-in user login functionality now. I\'m able to register an user in the registration view. If I try to login with t

相关标签:
1条回答
  • 2020-12-01 05:36

    The answer is right there in your code. What does this return?

    var userID = User.Identity.GetUserId();
    

    If you are using ASP.NET Identity, then after logging in (and redirecting to another page), the IPrincipal.IIdentity should be a ClaimsIdentity. You can try this:

    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;
        }
    }
    

    The above block of code is not exactly, but essentially, what the IIdentity.GetUserId extension method does.

    If none of this works, then the user may not really be logged into your site yet. After logging in, you have to redirect to another page before the server will write the authentication cookie to the browser. This cookie must be written before the User.Identity has all of this claims information (including the NameIdentifier) on subsequent requests.

    0 讨论(0)
提交回复
热议问题