userManagerAddToRole(User,Role) : System.InvalidOperationException:Role "Random Role Id string"不存在



我是实体框架和 ASP.NET MVC的新手。在我的项目中,我正在尝试为用户分配角色。当我尝试为用户分配角色时,会生成此错误。即使我试图在调试器中看到,我也得到了我所期望的角色 ID 和用户 ID,但是当这些id传递给userManager.AddToRole(User,Role)时,它说角色不存在。

这是我创建角色的种子方法。这些角色将在AspNetRoles表中创建。

internal sealed class Configuration : DbMigrationsConfiguration<VacationProjectV2.Models.ApplicationDbContext>
{
private RoleManagement roleManager;
private ApplicationDbContext dbContext;
public Configuration()
{
AutomaticMigrationsEnabled = false;
dbContext = new ApplicationDbContext();
roleManager = new RoleManagement(dbContext);
}
protected override void Seed(VacationProjectV2.Models.ApplicationDbContext context)
{
//  This method will be called after migrating to the latest version.C:UsersbrahmsourcereposVacationProjectV2VacationProjectV2App_Start
//  You can use the DbSet<T>.AddOrUpdate() helper extension method 
//  to avoid creating duplicate seed data.
roleManager.CreateRole("Admin")   //.ToString().ToUpper();
roleManager.CreateRole("ProjectManager")  //.ToString().ToUpper();
roleManager.CreateRole("Developer") //.ToString().ToUpper();
}
}

这是我的管理员控制器,我正在尝试分配它。

public class AdminsController : Controller
{
ApplicationDbContext db = new ApplicationDbContext();
UserManager<ApplicationUser> userManager;
RoleManager<IdentityRole> roleManager;
public AdminsController()
{
roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
}
// GET: Admins
public ActionResult AssignRole()
{
ViewBag.Users = new SelectList(db.Users, "Id", "UserName");
ViewBag.Roles = new SelectList(db.Roles, "Id", "Name");
return View();
}
[HttpPost]
public ActionResult AssignRole(string Users,String Roles)
{
userManager.AddToRole(Users, Roles);
ViewBag.Users = new SelectList(db.Users, "Id", "UserName");
ViewBag.Roles = new SelectList(db.Roles, "Id", "Name");
return View();
}
public ActionResult Index()
{
return View();
}
}

这里是View代码

@{
ViewBag.Title = "AssignRoles";
}
<h2>AssignRoles</h2>
@using (Html.BeginForm())
{
@Html.DropDownList("Users", "Select User");
@Html.DropDownList("Roles","Select Role")
<input type="Submit" value="Add Role"/>
}

所以我想在桌子AspNetUserRoles看到UserIdRoleId。我不知道我在哪里犯了错误。我试图通过看到另一个具有相同问题的帖子来使用.Tostrong().ToUpper()在种子方法中创建角色,但它对我不起作用。请让我知道我在哪里犯了错误。

对不起,伙计们 这是我的错,我没有正确检查方法所需的参数。错误是userManager.AddToRole().需要roleName而不是roleId作为参数。

public ActionResult AssignRoles()
{
ViewBag.Users = new SelectList(db.Users, "Id", "UserName");
ViewBag.Roles = new SelectList(db.Roles, "Name", "Name"); // Here I was Passing the Id insted Of Role Name.
return View();
}
[HttpPost]
public ActionResult AssignRoles(string Users,string Roles)
{
usersManager.AddToRole(Users, Roles);
ViewBag.Users = new SelectList(db.Users, "Id", "UserName");
ViewBag.Roles = new SelectList(db.Roles, "Name", "Name");
return View();
}

相关内容

  • 没有找到相关文章

最新更新