Reputation: 33
I'm new in Web APi, and I have app with token based authorization and users roles. I have controller which must get all users with role 'users'. Controller looks like:
public class UsersController : ApiController
{
public IEnumerable<ApplicationUser> GetUsersRoleUser ()
{
var context = new ApplicationDbContext();
var users = context.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains("601fd2b9-4a7f-4063-a831-e15978f05657")).ToList();
return users;
}}
That's good, and I get answer:
[was edited for @Ferri comment]
[{"Claims":[],
"Logins":[],
"Roles":[{"UserId":"2d9e98d4-2203-4f68-b8eb-6cac3c94cbd7","RoleId":"601fd2b9-4a7f-4063-a831-e15978f05657"}],
"Email":null,
"EmailConfirmed":false,
"PasswordHash":"AGMPpGJcGtD5",
"SecurityStamp":"ef896d77-e82a-4018-9023-1bf2e967e7bc",
"PhoneNumber":"+375445907729",
"PhoneNumberConfirmed":false,
"TwoFactorEnabled":false,
"LockoutEndDateUtc":null,
"LockoutEnabled":false,
"AccessFailedCount":0,
"Id":"2d9e98d4-2203-4f68-b8eb-6cac3c94cbd7",
"UserName":"sanya"},
{and another}]
How can I get array with values only "UserName"?
Upvotes: 0
Views: 80
Reputation: 64923
You need to use DTO design pattern. In your case, an anonymous type should be enough:
context.Users
.Where(x => x.Roles.Select(y => y.RoleId).Contains("601fd2b9-4a7f-4063-a831-e15978f05657"))
// Project each user into a DTO which just
// UserName property...
.Select(x => new { UserName = x.UserName })
.ToList()
Upvotes: 1