Aya Abdelaziz
Aya Abdelaziz

Reputation: 375

Get web api response with HttpClient MVC

I have an URL of API. I want to make an action in controller to get all data

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: ''
 }

It doesn't return any data but when I debug it , I have all data in innerTaslk.Result but var json equals null. so, I don't know why ?

Upvotes: 0

Views: 1613

Answers (1)

DavidG
DavidG

Reputation: 118937

You're trying to do async code without using async. That method is much simpler if you use proper async syntax. This should solve problems with how you are calling it:

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);
}

Upvotes: 3

Related Questions