Asp.net C# 添加用户角色
本文关键字:用户 角色 添加 net Asp | 更新日期: 2023-09-27 18:30:45
在我的应用程序中,我正在尝试添加角色,然后将用户添加到特定角色。在线搜索后,我制作了此片段
public ActionResult Install1()
{
ClearLocalDev();
RegisterBindingModel model = new RegisterBindingModel();
model.Email = "mohsin@crondale.com";
model.Password = "123Asd?";
model.ConfirmPassword = "123Asd?";
CreateUser(model);
return RedirectToAction("Index", "Home");
}
public void CreateUser(RegisterBindingModel model)
{
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult identityRoleResult;
IdentityResult identityUserResult;
var roleStore = new RoleStore<IdentityRole>(context); // The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
var roleMgr = new RoleManager<IdentityRole>(roleStore);
if (!roleMgr.RoleExists("Admin"))
{
identityRoleResult = roleMgr.Create(new IdentityRole { Name = "Admin" });
}
var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var appUser = new ApplicationUser
{
UserName = model.Email,
Email = model.Email
};
identityUserResult = userMgr.Create(appUser, model.Password);
if (!userMgr.IsInRole(userMgr.FindByEmail(model.Email).Id, "Admin"))
{
identityUserResult = userMgr.AddToRole(userMgr.FindByEmail(model.Email).Id, "Admin");
}
}
这不行。我有一个例外。请参阅代码中的注释,了解错误的内容和位置。
它与异步有关吗?
我正在使用 Azure 作为我的数据存储。
这应该适用于 4.5:
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult identityRoleResult;
IdentityResult identityUserResult;
var roleStore = new RoleStore<IdentityRole>(context);
var roleMgr = new RoleManager<IdentityRole>(roleStore);
if (!roleMgr.RoleExists("SuperAdmin"))
{
identityRoleResult = roleMgr.Create(new IdentityRole { Name = "SuperAdmin" });
}
var userMgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var appUser = new ApplicationUser
{
UserName = "SuperAdminUser@wingtiptoys.com",
Email = "SuperAdminUser@wingtiptoys.com"
};
identityUserResult = userMgr.Create(appUser, "Pa$$word1");
if (!userMgr.IsInRole(userMgr.FindByEmail("SuperAdminUser@xyz.com").Id, "SuperAdmin"))
{
identityUserResult = userMgr.AddToRole(userMgr.FindByEmail("SuperAdminUser@wingtiptoys.com").Id, "SuperAdmin");
}
是否已通过运行 ef 迁移为标识提供者创建了适当的数据库表? 对我来说,您似乎正在尝试在尚未创建基础数据库表时调用上下文。
我怀疑以下行也会导致问题:
identityUserResult = userMgr.Create(appUser, model.Password);
您需要检查两件事:
- 在尝试保存密码之前,您必须对密码进行哈希处理
- 在尝试保存密码之前,密码必须遵循配置的密码策略。