我已经安装了asp.net身份示例https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples并尝试使用用户“Sadmin@example.com”创建一个新角色“SAdmin”。用户已创建,但“Sadmin”与“Admin”
具有相同的角色我已将IdentityConfig.cs修改为
//Create User=Admin@Admin.com with password=Admin@123456 in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db) {
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string name = "admin@example.com";
const string password = "Admin@123456";
const string roleName = "Admin";
const string Sname = "Sadmin@example.com";
const string Spassword = "SAdmin@123456";
const string SroleName = "SAdmin";
//Create Super if it does not exist
var Srole = roleManager.FindByName(SroleName);
if (Srole == null)
{
Srole = new IdentityRole(roleName);
var roleresult = roleManager.Create(Srole);
}
var Suser = userManager.FindByName(Sname);
if (Suser == null)
{
Suser = new ApplicationUser { UserName = Sname, Email = Sname };
var result = userManager.Create(Suser, Spassword);
result = userManager.SetLockoutEnabled(Suser.Id, false);
}
// Add Suser to Role Admin if not already added
var SrolesForUser = userManager.GetRoles(Suser.Id);
if (!SrolesForUser.Contains(Srole.Name))
{
var result = userManager.AddToRole(Suser.Id, Srole.Name);
}
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null) {
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null) {
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name)) {
var result = userManager.AddToRole(user.Id, role.Name);
}
}
答案 0 :(得分:0)
问题在于代码......以下代码块负责
if (Srole == null)
{
**Srole = new IdentityRole(roleName);**
var roleresult = roleManager.Create(Srole);
}
将突出显示的行更改为
**Srole = new IdentityRole(SroleName);**
那应该解决它