Creating Roles in Asp.net Identity MVC 5

前端 未结 11 1373
情深已故
情深已故 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: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(new ApplicationDbContext());
      var roleManager = new RoleManager(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.

提交回复
热议问题