Creating Roles in Asp.net Identity MVC 5

前端 未结 11 1366
情深已故
情深已故 2020-12-02 05:09

There is very little documentation about using the new Asp.net Identity Security Framework.

I have pieced together what I could to try and create a new Role and add

相关标签:
11条回答
  • 2020-12-02 05:45

    I wanted to share another solution for adding roles:

    <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" />
    }
    

    Controller:

        [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();
        }
    
    0 讨论(0)
  • 2020-12-02 05:53

    Verify you have following signature of your MyContext class

    public class MyContext : IdentityDbContext<MyUser>

    Or

    public class MyContext : IdentityDbContext

    The code is working for me, without any modification!!!

    0 讨论(0)
  • 2020-12-02 05:53

    My application was hanging on startup when I used Peter Stulinski & Dave Gordon's code samples with EF 6.0. I changed:

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

    to

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

    Which makes sense when in the seed method you don't want instantiate another instance of the ApplicationDBContext. This might have been compounded by the fact that I had Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); in the constructor of ApplicationDbContext

    0 讨论(0)
  • 2020-12-02 05:54

    the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.

    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();
    
    0 讨论(0)
  • 2020-12-02 05:57

    If you are using the default template that is created when you select a new ASP.net Web application and selected Individual User accounts as Authentication and trying to create users with Roles so here is the solution. In the Account Controller's Register method which is called using [HttpPost], add the following lines in if condition.

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

    This will create first create a role in your database and then add the newly created user to this role.

    0 讨论(0)
提交回复
热议问题