我使用此处的教程将用户数据库的主键从字符串更改为int ,但是在初始化角色管理器时遇到了困难。它曾经使用
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
如何使用新数据创建角色管理器?
更新:我正在使用MVC 5和EF 6。
您ApplicationRoleManager
可能看起来像这样。因为您必须继承自customRole类而不是IdentityRole
。
public class ApplicationRoleManager : RoleManager<CustomRole, int>
{
public ApplicationRoleManager(IRoleStore<CustomRole, int> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<CustomRole, int, CustomUserRole>(context.Get<ApplicationDbContext>()));
}
}
然后将以下代码添加到Startup.Auth.cs类(如果当前不存在)。
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
然后,您可以创建和管理角色。
var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new CustomRole();
role.Id = 1; // this will be integer
role.Name = roleName;
var roleresult = roleManager.Create(role);
}
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句