问题
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
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/20858599/how-to-get-roles-from-using-simplemembership