在Asp.net Identity MVC中创buildangular色5

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

我拼凑了我可以尝试创build一个新的angular色,并添加一个用户。 我尝试了以下内容: 在ASP.NET身份中添加angular色

看起来它可能已经从这个博客中获得了信息: 用asp.net标识构build一个简单的待办事项应用程序,并将用户与待办事项

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

mscorlib.dll中发生System.InvalidOperationException实体typesIdentityRole不是当前上下文的模型的一部分。

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

任何帮助表示赞赏。

validation你有MyContext类的签名

public class MyContext : IdentityDbContext<MyUser>

要么

public class MyContext : IdentityDbContext

代码正在为我工​​作,没有任何修改!

开始了:

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

以下是描述如何使用ASP.NET身份创buildangular色,修改angular色,删除angular色和pipe理angular色的完整文章。 这还包含用户界面,控制器方法等

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

希望这个帮助

谢谢

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

创buildApplicationRoleManager (与ApplicationUser创build的模板类似)

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

要创build新的angular色,请从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 { } 

作为Peters代码上面的一个改进,你可以使用这个:

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

当我使用Peter Stulinski&Dave Gordon的EF 6.0代码示例时,我的应用程序正在启动。 我变了:

 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另一个实例时,这是有意义的。 这可能是因为我有Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());ApplicationDbContext的构造函数中

angular色查看模型

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

我想分享另一个添加angular色的解决scheme:

 <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(); } 
  public static void createUserRole(string roleName) { if (!System.Web.Security.Roles.RoleExists(roleName)) { System.Web.Security.Roles.CreateRole(roleName); } } 

我用于创buildangular色的方法如下,也列出了将它们分配给代码中的用户。 下面的代码在migrations文件夹的“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();