i would like add roles and use this roles in my ASP.NET Core Webapi. Can someone send me a exemple code? The Name of the Role is Admin
.
Asked
Active
Viewed 1,568 times
1

einerixcode
- 35
- 6
1 Answers
1
Use UserManger to get.
Like UserManger<ApplicationUser>
where ApplicationUser
class would be like this.
public class ApplicationUser : IdentityUser
{
[Required]
public override string UserName { get; set; }
[Required]
public override string Email { get; set; }
[Required]
public override string PhoneNumber { get; set; }
public string Address { get; set; }
[Required]
public bool IsActive { get;set; }
[Required]
public DateTime PwdExpiryDt { get; set; }
[Required]
public bool PwdExpiryFlg { get; set; }
[Required]
public DateTime LastPwdChgDt { get; set; }
[Required]
public DateTime CreatedDt { get; set; }
[Required]
public DateTime ModifiedDt { get; set; }
[Required]
public string CreatedBy { get; set; }
[Required]
public string ModifiedBy { get; set; }
}
Use _userManager like this
private readonly UserManager<ApplicationUser> _userManager;
Add role to user like this
IdentityResult identityResult = await _userManager.AddToRoleAsync(user, applicationRole.Name);
In your case, you can use RoleManger
also.
private readonly RoleManager<ApplicationRole> _roleManager;
var role = _roleManager.Roles.Single(r => r.Name == existingRole)
Role class would be like this.
public class ApplicationRole : IdentityRole
{
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedBy { get; set; }
public string IPAddress { get; set; }
}

prisar
- 3,041
- 2
- 26
- 27
-
Do you can send me a example? – einerixcode Oct 02 '18 at 08:42
-
In what for a class must i take the RoleManager? In Startup.cs? – einerixcode Oct 02 '18 at 09:01
-
And he can find the existingRole in var role = _roleManager.Roles.Single(r => r.Name == `existingRole`); – einerixcode Oct 02 '18 at 09:07
-
1existingRole = "Admin" – prisar Oct 02 '18 at 09:10
-
What do you meant with user in `_userManager.AddToRoleAsync(user, applicationRole.Name); ` – einerixcode Oct 02 '18 at 16:04
-
1You can add net role to the user – prisar Oct 02 '18 at 17:15
-
when i use the var role i become a `NullReferenceException: Object reference not set to an instance of an object` – einerixcode Oct 03 '18 at 15:57