Asp.net c#添加用户角色

时间:2016-01-18 11:58:14

标签: c# asp.net

在我的应用程序中,我尝试添加角色,然后将用户添加到特定角色。在线搜索后,我已经制作了这个片段

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");
    }

}

这没有得到。我得到一个例外。请参阅代码中的注释,以查看错误的内容和位置。

是否与Async有关?

我使用Azure作为我的数据存储。

2 个答案:

答案 0 :(得分:1)

这适用于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");
}

答案 1 :(得分:0)

您是否通过运行ef迁移为身份提供商创建了适当的数据库表?对我来说,似乎您正在尝试在尚未创建基础数据库表的情况下调用上下文。

我怀疑以下行也会导致问题:

identityUserResult = userMgr.Create(appUser, model.Password);

您需要检查两件事:

  1. 在尝试保存密码之前,您必须哈希密码
  2. 在尝试保存密码之前,密码必须符合配置的密码策略。