繁体   English   中英

ASP.NET C#添加用户角色

[英]Asp.net c# Adding user roles

在我的应用程序中,我尝试添加角色,然后将用户添加到特定角色。 在网上搜索后,我创建了此片段

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

您需要检查两件事:

  1. 您必须先对密码进行哈希处理,然后再尝试保存它
  2. 密码在保存之前必须遵守配置的密码策略。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM