【问题标题】:How can i add a Identity Role in a ASP.NET Core Webapi如何在 ASP.NET Core Webapi 中添加身份角色
【发布时间】:2018-10-02 08:30:31
【问题描述】:

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

【问题讨论】:

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


    【解决方案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; }
    }
    

    【讨论】:

    • 你能给我发个例子吗?
    • 在什么课程中我必须使用 RoleManager?在 Startup.cs 中?
    • 并且他可以在var role = _roleManager.Roles.Single(r => r.Name == existingRole)中找到existingRole;
    • existingRole = "管理员"
    • 可以给用户添加网络角色
    猜你喜欢
    • 2021-01-29
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2017-10-15
    • 2021-10-10
    • 1970-01-01
    • 2020-12-01
    相关资源
    最近更新 更多