我是Web APi的新手,我有app基于令牌的授权和用户角色。 我有控制器,必须让所有用户都有角色'用户'。 控制器看起来像:
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;
}}
那很好,我得到答案:
[为@Ferri评论编辑]
[{"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}]
如何才能获得仅包含值的数组&#34; UserName&#34;?
答案 0 :(得分:1)
您需要使用DTO设计模式。在您的情况下,匿名类型应该足够了:
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()