0

I am really new to ASP.NET MVC programming and I am currently using the default template for a web application project that contains the methods for registering user, user management and so on including the db as well. However, is it possible for me to add roles manually in the default database as follows:

Adding roles manually

and get it working instead of using views to create roles?

2
  • Have you tried it? What was the result? Commented Nov 28, 2016 at 16:30
  • I did but I can't really retrieve the roles using ASP.NET IDENTITY Commented Nov 28, 2016 at 16:31

2 Answers 2

1

To add role to a user you first need to add a new role in AspNetRoles table (which you already did)
Then you need to insert the corresponding user's id and role id into AspNetUserRoles table

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, I did as well but how do I retrieve the role of the user logged in? @Steve
@Pow4Pow5 ((RolePrincipal)User).GetRoles(); or Roles.GetRolesForUser()
0

Identity 3 (ASP.NET Core)

Creating:

var role = await _roleManager.FindByNameAsync("Admin"); if (role == null) { role = new IdentityRole("Admin"); await _roleManager.CreateAsync(role); } 

Btw: Best to place your roles into a constants class.

Retrieving role of user: I used following extension method.

public static string GetUserRole(this ClaimsPrincipal principal) { if (principal == null) { throw new ArgumentNullException(nameof(principal)); } return principal.Claims.SingleOrDefault(c => c.Type == "role")?.Value; } 

Controller:

var role = User.GetUserRole(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.