Search code examples
c#.netasp.net-web-apiasp.net-coreasp.net-roles

How can i add a Identity Role in a ASP.NET Core Webapi


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.


Solution

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