Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 300
  • Last Modified:

Creating Roles in ASP.NET VS 2013

I have just made the leap to VS 2013.  New to the Identity model.  Trouble finding some clear instructions on creating an 'Admin" role and assigning a user to that role.  I should add the web site is a webforms site.
0
rrhandle8
Asked:
rrhandle8
1 Solution
 
Carl TawnSystems and Integration DeveloperCommented:
Assuming you are using the default role provider and context, you should be able to do something like:
// grab the context
ApplicationDbContext context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();

// create a new user
ApplicationUser user = new ApplicationUser() { UserName = "TestUser", Email = "test@testmail.com" };
IdentityResult result = UserManager.Create(user);

// create a role manager from the context
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

// check if the "Admin" role exists; if it doesn't, create it
IdentityRole role = roleManager.FindByName("Admin");
if (role == null)
{
    role = new IdentityRole("Admin");
    roleManager.Create(role);
}

// add the user to the role
UserManager.AddToRole(user.Id, role.Name);

Open in new window

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now