How to get RoleID in ASP.NET MVC

Is there a way to get the RoleId without directly accessing the DB? I know that we can get the 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 anyone have any ideas about this?

+3


source to share


4 answers


Not. The role provider is unaware of the data source. It can be a very slow web service or a super-luxurious NoSQL database. The provider doesn't know what your db is as primary key.

Sure. SqlMembershipProvider

does. But if the identification of this key could lead to violations in relation to the Liskovs Substitution Principle .



The role name must be unique. Therefore, you have to get it yourself from the database. Or why can't you just use the role name directly and not the db key?

+2


source


You have to add the aspnet_Roles table to your model and use a query (like LINQ) to get the roleId. You can change the MembershipProvider, but it takes more work.



+2


source


You can not. ASP.NET MVC does not allow you to get the RoleId with a standard functor, you must get it from the database using the role name.

0


source


I realize this is a few years old, but when I ran into this, I saw that no one actually answered the question completely ... so I thought I'd post a complete solution.

Soooo ...

Simply put:

SELECT RoleId, RoleName FROM aspnet_Roles;
GO

      

But to get RoleIds for the user it looks 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 list of 2 columns RoleIds and RoleNames for a specific user.

You shouldn't actually try to do this, as there is a potential security breach when opening RoleId. You should only work with RoleNames and use Membership and Roles methods to manage things.

Hope it helps :)

0


source







All Articles