How to get current UserId in Identity 3.0? User.Ge

2019-04-27 04:02发布

问题:

I need to get ID of user that made some request. In previous versions of Identity I could do it like this:

User.Identity.GetUserId();

But it seems it isn't available anymore.

There is also something like:

User.GetUserId();

But it always returns null, even if User.Identity.IsAuthenticated in true and User.Identity.Name is set correctly.

What should I use to do it?

EDIT: My authenticaton logic is based on [default Visual Studio 2015 template], I hadn't changed much so far in identity, so if you want to check how is it done, you can simply see it on github link I pasted.

回答1:

Following our discussion, it seems your user identity does not contain the correct claim used by User.GetUserId().

Here is how you can manually set the NameIdentifier claim:

// ClaimsIdentity identity = new ClaimsIdentity...

identity.AddClaim(ClaimTypes.NameIdentifier, user.Id);


回答2:

I think there was a built in extension method for that in previous versions but they removed it. you can implement your own to replace it:

using System;
using System.Security.Claims;
using Microsoft.AspNet.Identity;

namespace cloudscribe.Core.Identity
{
    public static class ClaimsPrincipalExtensions
    {
        public static string GetUserId(this ClaimsPrincipal principal)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }
            var claim = principal.FindFirst(ClaimTypes.NameIdentifier);
            return claim != null ? claim.Value : null;
        }
    }
}

ClaimType.NameIdentifier should map to userid



回答3:

@Joe Audette

it turns out it has been move to other place.

User.GetUserId => UserManager.GetUserId(User)
User.GetUserName => UserManager.GetUserName(User)
User.IsSignedIn => SignInManager.IsSignedIn(User)

detail on github



回答4:

User.Identity.GetUserId(); Is available inside a class that inherits Page.



回答5:

You can also use

User.Identity.Name;

For more information go to MSDN

https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=vs.110).aspx