【发布时间】:2018-10-02 08:30:31
【问题描述】:
我想在我的 ASP.NET Core Webapi 中添加角色并使用此角色。有人可以给我一个示例代码吗?角色的名称是Admin。
【问题讨论】:
标签: c# .net asp.net-web-api asp.net-core asp.net-roles
我想在我的 ASP.NET Core Webapi 中添加角色并使用此角色。有人可以给我一个示例代码吗?角色的名称是Admin。
【问题讨论】:
标签: c# .net asp.net-web-api asp.net-core asp.net-roles
使用 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; }
}
【讨论】:
existingRole)中找到existingRole;