Как добавить идентификационную роль в ASP.NET Core Webapi? - PullRequest
0 голосов
/ 02 октября 2018

Я хотел бы добавить роли и использовать эти роли в моем ASP.NET Core Webapi.Может кто-нибудь прислать мне пример кода?Имя роли: Admin.

1 Ответ

0 голосов
/ 02 октября 2018

Используйте 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; }
}
...