tutorial net mvc framework asp and c# asp.net asp.net-mvc-5 asp.net-identity

c# - net - mvc roles authorization



Identidad ASP.NET: obtener todos los usuarios en un rol (5)

¿Cómo obtener una lista de todos los usuarios en un rol? Antes era posible con Roles.GetUsersInRole, pero con la nueva identidad no puedo encontrar nada como esto.


No es posible a través de RoleManager en 1.0 RTM, en 1.1 se expondrá a través de un IQueryable RoleManager.Roles. Para 1.0, debe bajar a la capa de implementación (es decir, contexto db)


Puede usar Entity Framework pero con Asp.Net Identity 1.0 aún no es posible. Tienes que esperar el lanzamiento de Identity 2.0.

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString)) { string queryString = "SELECT AspNetUsers.UserName FROM dbo.AspNetUsers INNER JOIN dbo.AspNetUserRoles ON " + "AspNetUsers.Id=AspNetUserRoles.UserId WHERE AspNetUserRoles.RoleID=''" + id + "''"; SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); List<string> @out = null; dynamic reader = command.ExecuteReader(); while (reader.Read()) { if (@out == null) @out = new List<string>(); @out.Add(reader.GetString(0)); } return @out; }


No vi un camino integrado, pero es bastante fácil de implementar. Tengo este método en mi UserManager específico de la aplicación:

public IQueryable<User> GetUsersInRole(string roleName) { return from user in Users where user.Roles.Any(r => r.Role.Name == roleName) select user; }

El SQL que salió parecía razonable:

SELECT [Extent1].[Id] AS [Id], [Extent1].[Email] AS [Email], [Extent1].[EmailConfirmed] AS [EmailConfirmed], [Extent1].[PasswordHash] AS [PasswordHash], [Extent1].[SecurityStamp] AS [SecurityStamp], [Extent1].[PhoneNumber] AS [PhoneNumber], [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed], [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled], [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc], [Extent1].[LockoutEnabled] AS [LockoutEnabled], [Extent1].[AccessFailedCount] AS [AccessFailedCount], [Extent1].[UserName] AS [UserName] FROM [dbo].[AspNetUsers] AS [Extent1] WHERE EXISTS (SELECT 1 AS [C1] FROM [dbo].[AspNetUserRoles] AS [Extent2] INNER JOIN [dbo].[AspNetRoles] AS [Extent3] ON [Extent2].[RoleId] = [Extent3].[Id] WHERE ([Extent1].[Id] = [Extent2].[UserId]) AND ([Extent3].[Name] = @p__linq__0) )


Esto es para la nueva MVC 5 ASP.NET Identity :

var managerRole = TMRoles.GetIdentityRole(TMRoles.Manager); var managers = managerRole.Users; public class TMRoles { private static RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new TMContext())); public static string Manager { get { return "Manager"; } } public static IdentityRole GetIdentityRole(string roleName) { return RoleManager.FindByName(roleName); } }


Por alguna razón, la muy buena consulta sugerida anteriormente por @ChoptimusPrime no compiló para mí en ASP.NET Identity 2.2.1. He escrito una función extendida:

public static IQueryable<User> GetUsersInRole(DbContext db, string roleName) { if (db != null && roleName != null) { var roles = db.Roles.Where(r => r.Name == roleName); if (roles.Any()) { var roleId = roles.First().Id; return from user in db.Users where user.Roles.Any(r => r.RoleId == roleId) select user; } } return null; }