Search code examples
c#asp.net-core.net-coreasp.net-identity

Add UserClaim with Identity asp.net core


In my class I call ApplicationRole and ApplicationUser as:

private readonly RoleManager<ApplicationRole> _roleManager;
private readonly UserManager<ApplicationUser> _userManager;
public Guid RoleId { get; set; }
public Guid UserId { get; set; }

public AssignRoleToUserModel(
    RoleManager<ApplicationRole> roleManager,
    UserManager<ApplicationUser> userManager)
{
    _roleManager = roleManager;
    _userManager = userManager;
}

And I have a method to assign roles to users like:

public async Task<IActionResult> OnPost(RoleToUserModel model)
{
    var roleId = model.RoleId.ToString();
    var userId = model.UserId.ToString();
    var role = await _roleManager.FindByIdAsync(roleId);
    var roleName = role.Name;
    var user = await _userManager.FindByIdAsync(userId);
    await _userManager.AddToRoleAsync(user, roleName);
    return  RedirectToPage();
}

So in other words. I add new register to UserRole table with this

await _userManager.AddToRoleAsync(user, roleName);

My question is, what is the method to add new register to UserClaim table? Regards


Solution

  • You have almost everything, you only need a claim you are going to assign to the user.

    await _userManager.AddClaimAsync(user,claim)