【问题标题】:Creating Roles in Asp.net Identity MVC 5在 Asp.net Identity MVC 5 中创建角色
【发布时间】:2013-11-10 21:51:00
【问题描述】:

关于使用新的 Asp.net 身份安全框架的文档很少。

我拼凑了我可以尝试创建一个新角色并向其中添加一个用户的内容。我尝试了以下方法:Add role in ASP.NET Identity

看起来它可能从这个博客中得到了信息:building a simple to-do application with asp.net identity and associating users with to-does

我已将代码添加到数据库初始化程序中,该程序会在模型更改时运行。它在 RoleExists 函数上失败,并出现以下错误:

System.InvalidOperationException 出现在 mscorlib.dll 中 实体类型 IdentityRole 不是当前上下文模型的一部分。

protected override void Seed (MyContext context)
{
    var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); 
    var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

    // Create Admin Role
    string roleName = "Admins";
    IdentityResult roleResult;

    // Check to see if Role Exists, if not create it
    if (!RoleManager.RoleExists(roleName))
    {
        roleResult = RoleManager.Create(new IdentityRole(roleName));
    }
}

感谢任何帮助。

【问题讨论】:

    标签: c# asp.net-mvc-5 asp.net-identity


    【解决方案1】:

    我们开始吧:

    var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    
    
       if(!roleManager.RoleExists("ROLE NAME"))
       {
          var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
          role.Name = "ROLE NAME";
          roleManager.Create(role);
    
        }
    

    【讨论】:

    • 这对我很有帮助,尤其是因为我没有使用迁移。我正在使用 DropCreateDatabaseAlways。
    • 我的问题是我使用了错误的上下文。我创建了两个连接字符串,一个名为 IdentityDbContext,另一个我使用的是自定义上下文,所以当我使用您的建议 AppilcationDbContext() 时,它起作用了。
    • var roleManager = new RoleManager(new RoleStore(db));
    【解决方案2】:

    验证您有以下MyContext 类的签名

    public class MyContext : IdentityDbContext&lt;MyUser&gt;

    或者

    public class MyContext : IdentityDbContext

    代码为我工作,无需任何修改!!!

    【讨论】:

    • 感谢大家的回复。现在一切正常。检查上下文使我朝着正确的方向前进。创建 asp.net 身份时,它会创建一个扩展 IdentityDbContext 的新上下文 (ApplicationDbContext)。在我的代码中,我引用了未扩展 IdentityDbContext 的原始上下文。如果其他人遇到此问题,请检查您的上下文并仔细检查您的 APP_DATA 目录,以确保您不会意外创建两个数据库。
    【解决方案3】:

    这是描述如何使用 ASP.NET Identity 创建角色、修改角色、删除角色和管理角色的完整文章。这还包含用户界面、控制器方法等。

    http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

    希望对你有帮助

    谢谢

    【讨论】:

    • 你的博客不错,但是过时了,能不能更新一下账号控制器
    • 它已经适用于 ASP.NET MVC 5(您正在寻找 aggie 的什么更新?)。您可以从文章中指定的 GitHub 链接下载源代码。
    • 其中一些功能在最新的 2.2.0 中似乎已被弃用。 1) 我可以在当前版本中使用相同的代码吗 2) 我如何将主键从 Guid 更改为电子邮件 3) 关于如何将 recpatcha 与 Identity 集成的任何建议将不胜感激j.mp/1nohaHe
    【解决方案4】:

    ASP.NET 5 rc1-final,我做了以下操作:

    创建ApplicationRoleManager(与模板创建ApplicationUser类似)

    public class ApplicationRoleManager : RoleManager<IdentityRole>
    {
        public ApplicationRoleManager(
            IRoleStore<IdentityRole> store,
            IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
            ILookupNormalizer keyNormalizer,
            IdentityErrorDescriber errors,
            ILogger<RoleManager<IdentityRole>> logger,
            IHttpContextAccessor contextAccessor)
            : base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
        {
        }
    }
    

    Startup.cs中的ConfigureServices,我将其添加为RoleManager

    services.
        .AddIdentity<ApplicationUser, IdentityRole>()
        .AddRoleManager<ApplicationRoleManager>();
    

    要创建新角色,请从Configure 拨打以下电话:

    public static class RoleHelper
    {
        private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
        {
            if (!await roleManager.RoleExistsAsync(roleName))
            {
                await roleManager.CreateAsync(new IdentityRole(roleName));
            }
        }
        public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
        {
            // add all roles, that should be in database, here
            await EnsureRoleCreated(roleManager, "Developer");
        }
    }
    
    public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
    {
         ...
         await roleManager.EnsureRolesCreated();
         ...
    }
    

    现在,可以将规则分配给用户

    await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");
    

    或者用在Authorize属性中

    [Authorize(Roles = "Developer")]
    public class DeveloperController : Controller
    {
    }
    

    【讨论】:

    • services.AddIdentity&lt;UserAuth, IdentityRole&gt;().AddRoleManager&lt;ApplicationRoleManager&gt;() 我无法直接将其添加到services
    • @AlexC,对不起,我的错。我试图让它尽可能简单,并删除了 AddIdentity。固定。
    • 因此,我已将该代码添加到独立项目github.com/AlexChesser/AspnetIdentitySample/commit/… 中,并且 AspnetRoles 确实成功创建,但由于某种原因,页面变为“白屏”(我假设出现 500 错误,但没有堆栈跟踪)你是否能够在安装了这个的情况下呈现页面?
    • ok - 此提交修复了白屏错误github.com/AlexChesser/AspnetIdentitySample/commit/… 请注意,在 EnsureRolesCreated 中,我已将其切换为 void 而不是 Task。
    • 具有 'EnsureRolesCreated' 返回 void 可能意味着在配置完成之前未创建角色
    【解决方案5】:

    作为对上述 Peters 代码的改进,您可以使用以下代码:

       var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    
       if (!roleManager.RoleExists("Member"))
                roleManager.Create(new IdentityRole("Member"));
    

    【讨论】:

      【解决方案6】:

      当我在 EF 6.0 中使用 Peter Stulinski 和 Dave Gordon 的代码示例时,我的应用程序在启动时挂起。我改变了:

      var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
      

      var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(**context**));
      

      当您不想在种子方法中实例化ApplicationDBContext 的另一个实例时,这很有意义。这可能是由于我在 ApplicationDbContext 的构造函数中有 Database.SetInitializer&lt;ApplicationDbContext&gt;(new ApplicationDbInitializer()); 的事实而复杂化了

      【讨论】:

        【解决方案7】:

        角色视图模型

        public class RoleViewModel
        {
            public string Id { get; set; }
            [Required(AllowEmptyStrings = false)]
            [Display(Name = "RoleName")]
            public string Name { get; set; }
        }
        

        控制器方法

            [HttpPost]
            public async Task<ActionResult> Create(RoleViewModel roleViewModel)
            {
               if (ModelState.IsValid)
               {
                   var role = new IdentityRole(roleViewModel.Name);
                   var roleresult = await RoleManager.CreateAsync(role);
                   if (!roleresult.Succeeded)
                   {
                       ModelState.AddModelError("", roleresult.Errors.First());
                       return View();
                   }
                   return RedirectToAction("some_action");
               }
               return View();
            }
        

        【讨论】:

          【解决方案8】:

          我想分享另一个添加角色的解决方案:

          <h2>Create Role</h2>
          
          @using (Html.BeginForm())
          {
          @Html.AntiForgeryToken()
          @Html.ValidationSummary(true)
          <span class="label label-primary">Role name:</span>
          <p>
              @Html.TextBox("RoleName", null, new { @class = "form-control input-lg" })
          </p>
          <input type="submit" value="Save" class="btn btn-primary" />
          }
          

          控制器:

              [HttpGet]
              public ActionResult AdminView()
              {
                  return View();
              }
          
              [HttpPost]
              public ActionResult AdminView(FormCollection collection)
              {
                  var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
          
                  if (roleManager.RoleExists(collection["RoleName"]) == false)
                  {
                      Guid guid = Guid.NewGuid();
                      roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] });
                  }
                  return View();
              }
          

          【讨论】:

            【解决方案9】:

            如果您使用的是当您选择新的 ASP.net Web 应用程序并选择个人用户帐户作为身份验证并尝试使用角色创建用户时创建的默认模板,那么这里是解决方案。在使用 [HttpPost] 调用的 Account Controller 的 Register 方法中,在if condition 中添加以下行。

            使用 Microsoft.AspNet.Identity.EntityFramework;

            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            
            var result = await UserManager.CreateAsync(user, model.Password);
            
            if (result.Succeeded)
            {
              var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
              var roleManager = new RoleManager<IdentityRole>(roleStore);
              if(!await roleManager.RoleExistsAsync("YourRoleName"))
                 await roleManager.CreateAsync(new IdentityRole("YourRoleName"));
            
              await UserManager.AddToRoleAsync(user.Id, "YourRoleName");
              await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
              return RedirectToAction("Index", "Home");
            }
            

            这将首先在您的数据库中创建一个角色,然后将新创建的用户添加到该角色中。

            【讨论】:

              【解决方案10】:
                  public static void createUserRole(string roleName)
                  {
                      if (!System.Web.Security.Roles.RoleExists(roleName))
                      {
                          System.Web.Security.Roles.CreateRole(roleName);
                      }
                  }
              

              【讨论】:

                【解决方案11】:

                我用于创建角色的方法如下,也列出了在代码中将它们分配给用户。以下代码确实在迁移文件夹的“configuration.cs”中。

                string [] roleNames = { "role1", "role2", "role3" };
                var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
                
                                IdentityResult roleResult;
                                foreach(var roleName in roleNames)
                                {
                                    if(!RoleManager.RoleExists(roleName))
                                    {
                                        roleResult = RoleManager.Create(new IdentityRole(roleName));
                                    }
                                }
                                var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                                UserManager.AddToRole("user", "role1");
                                UserManager.AddToRole("user", "role2");
                                context.SaveChanges();
                

                【讨论】:

                  猜你喜欢
                  • 2016-10-24
                  • 2016-03-14
                  • 2015-02-01
                  • 2013-12-26
                  • 2015-07-21
                  • 2014-04-23
                  • 1970-01-01
                  • 2014-12-19
                  • 1970-01-01
                  相关资源
                  最近更新 更多