Инициализация RoleManager в Identity ASP.NET с настраиваемыми ролями
Я изменил первичный ключ для пользовательской базы данных из строки в int, используя учебник здесь, но мне трудно инициализировать Role Manager. Он использовался для инициализации с использованием
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
Как создать диспетчер ролей с помощью новых данных?
Обновление: я использую MVC 5 и EF 6.
Ответы
Ответ 1
Ваш ApplicationRoleManager
может выглядеть так. потому что вы должны наследовать свой собственный классRole вместо 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);
}
Надеюсь, что это поможет.
Ответ 2
Из вашего вопроса я не могу определить, используете ли вы одни и те же структуры (MVC и EF).
Недавно я создал решение MVC + EF, используя пользовательские ApplicationUsers и IdentityRoles.
ApplicationUser происходит от "Microsoft.AspNet.Identity.EntityFramework.IdentityUser".
ApplicationRoles реализованы без изменений.
У меня есть следующий класс:
// Configure the used in the application. RoleManager is defined in the ASP.NET Identity core assembly
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
}
}
внутри configuration.cs(migrations) == > on 'update-database' это будет выполнено
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var applicationRoleAdministrator = new IdentityRole("Administrator");
if (!roleManager.RoleExists(applicationRoleAdministrator.Name))
{
roleManager.Create(applicationRoleAdministrator);
}
// do some logic to find your applicationUserAdministrator
var applicationUserAdministrator = userManager.FindByName("Administrator");
userManager.AddToRole(applicationUserAdministrator.Id, applicationRoleAdministrator.Name);
с командой startup.auth.cs привязка к RoleManager:
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
Ответ 3
Надеюсь, что это поможет.
var roleManager = new RoleManager<CustomRole,int>(new RoleStore<CustomRole,int,CustomUserRole>(context));
var UserManager = new UserManager<ApplicationUser,int>(new UserStore<ApplicationUser,CustomRole,int,CustomUserLogin,CustomUserRole,CustomUserClaim>(context));
// In Startup iam creating first Admin Role and creating a default Admin User
if (!roleManager.RoleExists("Admin")){
//first we create Admin rool
var role = new CustomRole();
role.Name = "Admin";
roleManager.Create(role);
}
////Here we create a Admin super user who will maintain the website
if (UserManager.FindByName("Admin") == null){
var user = new ApplicationUser() { UserName = "Admin" };
string userPWD = "adminadmin";
var chkUser = UserManager.Create(user, userPWD);
if (chkUser.Succeeded){
var result1 = UserManager.AddToRole(user.Id, "Admin")
;
}
}