是否有可能使用Identity来保存带枚举参数的角色?
我正在尝试创建带身份的授权。是否有可能使用Identity来保存带枚举参数的角色?
到目前为止eveything正在与我在网上找到的指导方针一起工作。
但是我想修改角色的保存。我创建了一个枚举,并将此枚举保存到aspNetRoles表(代码如下)。
作用被保存到用户的方式是通过以下事项:
UserManager.AddToRole(user.Id, "Admin");
我不是一个字符串作为第二paramater发送的粉丝,并希望派一个枚举来代替。
这可能吗?
我迄今为止代码:
修改aspnetRoles表通过添加自定义属性:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
new public DbSet<ApplicationRole> Roles { get; set; }
}
public class ApplicationRole : IdentityRole
{
[Required]
public RoleId roleId { get; set; }
}
public enum RoleId
{
Developer = 0,
Administrator = 1,
Other = 2
}
将在startup.cs作用:
if (!roleManager.RoleExists("Developer"))
{
// first we create Admin rool
var role = new ApplicationRole();
role.Name = "Developer";
role.roleId = RoleId.Developer;
roleManager.Create(role);
//Here we create a Admin super user who will maintain the website
var user = new ApplicationUser();
user.UserName = "ra3iden";
user.Email = "[email protected]";
user.FirstName = "Myname";
user.LastName = "LastName";
string userPWD = "[email protected]";
var chkUser = UserManager.Create(user, userPWD);
//Add default User to Role Admin
if (chkUser.Succeeded)
{
var result1 = UserManager.AddToRole(user.Id, "Developer");
}
}
正如我上面我所提到的不希望拥有角色名称属性,我想使用枚举,这是如何完成的?
编辑: PIC aspNetRoles的:
UserManager.AddToRole
是extension method,所以你可以写类似的方法给你的用户添加到您的角色:
public static IdentityResult AddToRole<TUser, TKey>(
this UserManager<TUser, TKey> manager,
TKey userId,
RoleId role
)
where TUser : class, Object, IUser<TKey>
where TKey : Object, IEquatable<TKey>
{
return manager.AddToRoleAsync(userId, role.ToString())
.Result;
}
但也许这种情况需要不同的方法。 "Admin"
不是一个魔术常数,但它是一个常数。如果你想重命名"Admin"
到"Administrator"
?字符串常量重命名操作很困难,可能存在错误。
你可以做什么是你的角色申报命名常量:
public static class Role
{
public const string Admin = "Admin";
public const string Developer = "Developer";
public const string Other = "Other";
}
. . .
UserManager.AddToRole(user.Id, Role.Admin);
public enum Roles
{
Developer,
Manager
}
if (!roleManager.RoleExists(Roles.Developer))
{
// first we create Admin rool
var role = new ApplicationRole();
role.Name = Roles.Developer;
role.roleId = RoleId.Developer;
roleManager.Create(role);
//Here we create a Admin super user who will maintain the website
var user = new ApplicationUser();
user.UserName = "ra3iden";
user.Email = "[email protected]";
user.FirstName = "Myname";
user.LastName = "LastName";
string userPWD = "[email protected]";
var chkUser = UserManager.Create(user, userPWD);
//Add default User to Role Admin
if (chkUser.Succeeded)
{
var result1 = UserManager.AddToRole(user.Id, Roles.developer);
}
}
如果添加Developer.ToString(),那么这将工作,但它超出了范围。我在问是否可以在不包含角色名称的情况下保存角色,只需使用我提供的枚举 – ThunD3eR
怎么样'RoleId.Developer.ToString()'呢? – DavidG
这将是一个快速修复。虽然我的意图不完全是这样,但如果案件只是不加硬编码字符串,那么这将解决问题,但如果我删除名称属性entierly,只专注于保存枚举? – ThunD3eR
那么你的枚举是否与角色ID匹配? – DavidG