2

I am developing a MVC4 application with SimpleMembership. I have a table - "userInfo" in which I am storing user's information such as Name, Email, Address, Phone, Role etc. When I register a user, data is stored in this table and webpages_Membership. No data is stored in other Membership tables (OAuthMembership, Roles, UserInRoles).

When I login a user, it is validated using :

if (ModelState.IsValid && WebSecurity.Login(Model.Name, Model.Password, false))

it returns "True" but after this, I need to get the role of the registered user.

In SimpleMembership, does "Roles and UserInRoles" table provide registered user role or can I query the "userInfor" table and get roles from this table.

Please advice

Thanks in Advance

EfrainReyes
  • 1,005
  • 2
  • 21
  • 55
ijs
  • 189
  • 1
  • 4
  • 11

2 Answers2

3

to get all available roles, assuming you have enabled Roles and added at least one..

var roles = (SimpleRoleProvider)Roles.Provider;

var allRoles = roles.GetAllRoles();

to get specific user's roles.

var userRoles = roles.GetRolesForUser("specificusername");

ref MSDN

Simple Membership does not come with any out of the box management pages for Roles. You are on your own to create them, or manage them directly through code/sql/ef etc..

Code examples...

Check for and creation of Admin role:

if (!Roles.RoleExists("Admin"))
     Roles.CreateRole("Admin");

Adding user to role on creation:

if (!Roles.GetRolesForUser("specificusername").Contains("Admin"))
     Roles.AddUsersToRoles(new[] {"specificusername"}, new[] {"Admin"});

ref adding-security-and-membership

Mike Ramsey
  • 843
  • 8
  • 23
  • Yes, I have enabled roles in Web.Config file. Could you tell me how to add role. When I register a new user, no role is created in the webpages_roles table. Is there a different approach to add a role? – ijs Jan 01 '14 at 06:12
  • 1
    The default code generated by the Internet template does not automatically add roles to a new user. You have to add the code for it. Try looking at the SimpleRoleProvider documentation http://msdn.microsoft.com/en-us/library/webmatrix.webdata.simpleroleprovider(v=vs.111).aspx . You can add a role by using the CreateRole method and map it to a user using AddUsersToRoles method. – Kevin Junghans Jan 02 '14 at 14:39
0

You can user Roles.GetRolesForUser Method after your user logged in

Gets a list of the roles that the currently logged-on user is in.

Or if you want to check whether current user is in specified role you can use Roles.IsUserInRole Method

Selman Genç
  • 100,147
  • 13
  • 119
  • 184