Get all roles of any user (yes, not currently logged one)

非 Y 不嫁゛ 提交于 2019-12-12 06:35:16

问题


In an MVC app, administrator has a CRUD controller for managing users. Now, the functionality of the edit part needs to be extended and it involves adding a number role dependent tabs. They depend on the role of the viewed user, rather than on roles of the administrator who is viewing them. The easiest way for achieving this, would be getting all roles of that user as a array of strings (or similar), but how do I actually go about obtain those.

Is there a preferred method of getting all roles of a single user in SimpleMembership (based on his UserId) or do I just have to patch up a stored function in the database and pull those through it?

Writing the function is not a big deal, but this problem doesn't sound like something I should have to make workarounds for.


回答1:


Use the Roles.GetRolesForUser() method https://msdn.microsoft.com/en-us/library/8h930x07(v=vs.110).aspx

string[] rolesArray = Roles.GetRolesForUser("username"); 

With the string being the User Name of the user as contained in the aspnetdb.

If you want to find by using a guid, you could try the following:

Guid userId; // ID of user - you can populate this somehow
MembershipUser memUser = Membership.GetUser(userId);
string[] roles = Roles.GetRolesForUser(memUser.UserName);



回答2:


Here is the stored procedure I mentioned in the question:

CREATE FUNCTION GetUserRoles
(
    @UserId int
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT
        r.RoleName
    FROM
        dbo.webpages_UsersInRoles uir
        JOIN dbo.webpages_Roles r ON (r.RoleId = uir.RoleId)
    WHERE
        uir.UserId = @UserId
)
GO

The only reason to go with this instead than the answer by user1666620, would be if you wanted to skip one unnecessary query to the DB. The preferred method to use this solution would be to add this function to your dbml (or it's EF equivalent). Obviously this first needs to be added in the database.



来源:https://stackoverflow.com/questions/28834128/get-all-roles-of-any-user-yes-not-currently-logged-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!