我正在使用asp.net mvc web api2控制器创建一个简单的api使用者应用程序。
我的web api控制器中的两个get请求如下:
public async Task<List<User>> GetUsersAsync()
{
using (HttpClient httpClient = new HttpClient())
{
return JsonConvert.DeserializeObject<List<User>>(
await httpClient.GetStringAsync("https://jsonplaceholder.typicode.com/posts")
);
}
}
public async Task<List<UserToDoList>> GetUserToDoListAsync()
{
using (HttpClient httpClient = new HttpClient())
{
return JsonConvert.DeserializeObject<List<UserToDoList>>(
await httpClient.GetStringAsync("http://jsonplaceholder.typicode.com/todos")
);
}
}
这给了我两个单独对象的列表用户列表&amp;用户待办事项列表。
将它们组合在一起的最佳/最快方式是什么,以便我可以以表格格式显示它:
UserId | Name | Count Of Todo's
答案 0 :(得分:1)
结合两个调用并通过调用web apis或创建合并数据并返回组合数据的新端点,在客户端返回您想要的内容
using (HttpClient httpClient = new HttpClient()) {
var users = JsonConvert.DeserializeObject<List<User>>(
await httpClient.GetStringAsync("https://jsonplaceholder.typicode.com/posts")
);
var todos = JsonConvert.DeserializeObject<List<UserToDoList>>(
await httpClient.GetStringAsync("http://jsonplaceholder.typicode.com/todos")
);
var result = from user in users
join todo in todos on user.UserId equals todo.UserId into userTodos
select new { UserId = user.UserId, Name = user.Name, CountOfTodos = userTodos.Count() };
}