Saeid
Saeid

Reputation: 13582

How Get RoleID in ASP.NET MVC

Is there any way to get RoleId without get directly from DB?, I know we can get role Names by:

string[] allRoles = System.Web.Security.Roles.GetAllRoles();
string[] allRolesForUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);

But I need to access roleId.

Does any one have any idea about it?

Upvotes: 3

Views: 4620

Answers (4)

Art
Art

Reputation: 1

I realize this is a few years old, but when i bumped into it I saw that noone actually answers completely answers the question ...so I thought I would post a full solution.

Soooo...

Simply put:

SELECT RoleId, RoleName FROM aspnet_Roles;
GO

But for getting RoleIds for a User it is like this:

SELECT UR.RoleID, R.RoleName FROM
aspnet_Users U, aspnet_Roles R, aspnet_UsersInRoles UR 
WHERE U.UserName = @Username 
AND UR.UserId = U.UserId 
AND UR.RoleID = R.RoleId
GO

This will give you a 2 column list of RoleIds and RoleNames for a particular user.

In reality, you should not be trying to do this as there is a potential for Security breach when a RoleId is exposed. You should only work with RoleNames and use the Membership and Roles methods to manage things.

Hope this helps :)

Upvotes: 0

Shayan
Shayan

Reputation: 402

You must add aspnet_Roles table to your model and use query (for example LINQ) to get roleId .You can change MembershipProvider but it need more work for doing it.

Upvotes: 2

Chuck Norris
Chuck Norris

Reputation: 15190

You can't. ASP.NET MVC doesn't allow to get RoleId with standard functon, you must get it from database with the help of role name.

Upvotes: 0

jgauffin
jgauffin

Reputation: 101150

No. The role provider have no knowledge about the data source. It can be a very slow web service or a super deluxe NoSQL database. The provider doesn't know that your db as a primary key.

Sure. The SqlMembershipProvider does. But having it exposing the key would likely lead to violations against Liskovs Substitution Principle.

The role name should be unique. So you should yourself be able to fetch it from the database. Or why can`t you simply use the role name directly instead of the db key?

Upvotes: 2

Related Questions