我有一个API的网址。我想在控制器中进行操作以获取所有数据
BranchesController.cs:
public Task<IEnumerable<BranchVm>> GetAllAsync()
{
string baseUrl = "http://api.diamond.smart-gate.net/api/Branches/GetBranches";
var client = new HttpClient();
var task = client.GetStringAsync(baseUrl);
return task.ContinueWith<IEnumerable<BranchVm>>(innerTask =>
{
var json = innerTask.Result;
return JsonConvert.DeserializeObject<BranchVm[]>(json);
});
}
Branch.js:
columns: [
{
"data": 'branchArName',
"name": "branchArName",
"autoWidth": true,
"orderable": true
},
{
"data": 'branchEnName',
"name": "branchEnName",
"autoWidth": true,
"orderable": true,
},
],
ajax: {
url: "/Branches/GetAllAsync",
dataSrc: ''
}
它不返回任何数据,但是当我调试它时,我在innerTaslk.Result中有所有数据,但var json等于null。所以,我不知道为什么?
答案 0 :(得分:2)
您尝试在不使用异步的情况下执行异步代码。如果使用正确的async
语法,那么该方法会更简单。这应该解决你如何调用它的问题:
public async Task<IEnumerable<BranchVm>> GetAllAsync()
// ^^^^^
// Make the method async
{
string baseUrl = "http://api.diamond.smart-gate.net/api/Branches/GetBranches";
var client = new HttpClient();
var json = await client.GetStringAsync(baseUrl);
// ^^^^^
// await the async call instead of messing around with tasks
return JsonConvert.DeserializeObject<BranchVm[]>(json);
}