我正在尝试使用Entity Framework在MVC5中播放管理员角色,似乎我们不再使用WebSecurity和SimpleRoleProvider。
我发现了一篇名为MVC5 Seed Roles and Users的精彩帖子。
我仔细阅读并尝试实施它,但我在两个方面遇到了麻烦。在提供的示例中,他们仅显示如何添加用户名,而网站需要电子邮件和密码才能注册。
以下是我以前在MVC4中的表现:
protected override void Seed(PhotoAlbum.Models.UsersContext context)
{
seedUserAccounts();
}
private void seedUserAccounts()
{
WebSecurity.InitializeDatabaseConnection("UsersContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);
SimpleRoleProvider roles = (SimpleRoleProvider)Roles.Provider;
if (!roles.RoleExists("admin"))
{
roles.CreateRole("admin");
}
SimpleMembershipProvider membership = (SimpleMembershipProvider)Membership.Provider;
if (membership.GetUser("account", false) == null)
{
membership.CreateUserAndAccount("account", "pass");
}
if (!roles.IsUserInRole("account", "admin"))
{
roles.AddUsersToRoles(new[] { "account" }, new[] { "admin" });
}
}
我想知道如何更改以下方法以允许使用电子邮件地址和密码。
protected override void Seed(BlogEngine.Models.ApplicationDbContext context)
{
if (!context.Roles.Any(r => r.Name == "Admin"))
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = "Admin" };
manager.Create(role);
}
if (!context.Users.Any(u => u.UserName == "myUsername"))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser { UserName = "myUsername" };
manager.Create(user, "ChangeItAsap!");
manager.AddToRole(user.Id, "Admin");
}
}
答案 0 :(得分:1)
正如史蒂夫格林上面所说的那样,我已经在那里......我确实做了一些改变。这是我的最终解决方案:
// makes an admin role if one doesn't exist
if (!context.Roles.Any(r => r.Name == "Admin"))
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
var role = new IdentityRole { Name = "Admin" };
manager.Create(role);
}
// if user doesn't exist, create one and add it to the admin role
if (!context.Users.Any(u => u.UserName == "admin"))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser { UserName = "me@me.com", Email = me@me.com" };
manager.Create(user, "password");
manager.AddToRole(user.Id, "Admin");
}