2016-10-30 31 views
0

我是Web APi中的新成员,我有基于令牌的授权和用户角色的应用程序。 我有控制器,必须让所有用户具有'用户'角色。 控制器的样子:从请求到数组获取值WebAPi

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}] 

我怎么能只得到数组值“用户名”?

+0

你能否在这个问题中粘贴你的完整的json结果? – Ferri

+0

好的,我粘贴。 – feofan

回答

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() 
+0

谢谢!但我不能返回一个匿名类型? – feofan

+0

@feofan你已经试过了吗? ; P –

+0

哦,是的,我尝试)但Visual Studio显示我不能隐藏“System.Collections.Generic.List <<匿名类型:字符串UserName >>”到“System.Collections.Generic.IEnumerable ”。 Omg,我做错了什么?) – feofan