0

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"?

2
  • Could you paste in this question your full json result? Commented Oct 30, 2016 at 10:39
  • Okay, I pasted. Commented Oct 30, 2016 at 11:55

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! But I can't return an anonymous type?
Oh yes, I try) But Visual studio show me error about can't covert "System.Collections.Generic.List<<anonymous type: string UserName>>" into "System.Collections.Generic.IEnumerable<AppName.Models.ApplicstionUser>". Omg, what I do wrong?)
@feofan Change your return value from IEnumerable<ApplicationUser> to IEnumerable<object>!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.