Huệ Vũ
Huệ Vũ

Reputation: 35

Get data from Personal Data in Identity User in ASP.Net Core

I have a class which inherits from Identity User, like this

public class ApplicationUser:IdentityUser
    {
        [PersonalData]
        public bool IsManager { get; set; }
        [PersonalData]
        public string FullName { get; set; }
        [PersonalData]
        public string UserNameBW { get; set; }
        [PersonalData]
        public int DepartmentId { get; set; }
    }

Now I want to access to FullName of current user, how could I do that.

I only get the name by User.Identity.Name.

Thanks in advance

Upvotes: 0

Views: 859

Answers (2)

Mehmet Zahid Tokat
Mehmet Zahid Tokat

Reputation: 11

No need to implement UserClaims

Add your Identity NameSpace

using Microsoft.AspNetCore.Identity

Then inject it with your inherited IdentityUser class

UserManager<ApplicationUser> _userManager

... injecting depends on where you are injecting

Then get current user like;

ApplicationUser user = await _userManager.FindByNameAsync(User.Identity.Name);

da daa... there it is:

user.Fullname;
user.IsManager;
user.UserNameBW;
user.DepartmentId;

all useable for you

Upvotes: 1

HMZ
HMZ

Reputation: 3127

You can create a custom claims principle factory, add your custom claims and register it.

Something like this

public class CustomClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser> 
{     
    public CustomClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager,
        IOptions<IdentityOptions> optionsAccessor)
            : base(userManager, optionsAccessor)     
    {
    }
      
    protected override async Task<ClaimsIdentity>GenerateClaimsAsync(ApplicationUser user)
    {
         var identity = await base.GenerateClaimsAsync(user);
         identity.AddClaim(new Claim("FullName", user.FullName));         
         return identity;     
    } 
}

Register it

other services... 
... 
AddEntityFrameworkStores<ApplicationDbContext>()
        .AddClaimsPrincipalFactory<CustomClaimsPrincipalFactory>();

and then use it like this

User.FindFirst("FullName").Value

Upvotes: 1

Related Questions