如何在ASP.NET Core Webapi中添加身份角色

时间:2018-10-02 08:30:32

标签: c# .net asp.net-web-api asp.net-core asp.net-roles

我想添加角色并在我的ASP.NET Core Webapi中使用此角色。有人可以给我发送示例代码吗?角色的名称为Admin

1 个答案:

答案 0 :(得分:1)

使用UserManger获取。

就像UserManger<ApplicationUser>,其中ApplicationUser类就是这样。

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

像这样使用_userManager

private readonly UserManager<ApplicationUser> _userManager;

像这样向用户添加角色

IdentityResult identityResult = await _userManager.AddToRoleAsync(user, applicationRole.Name);

根据您的情况,也可以使用RoleManger

private readonly RoleManager<ApplicationRole> _roleManager;

var role = _roleManager.Roles.Single(r => r.Name == existingRole)

角色类就是这样。

public class ApplicationRole : IdentityRole
{
    public string Description { get; set; }
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }
    public string IPAddress { get; set; }
}