【问题标题】:Get web api response with HttpClient MVC使用 HttpClient MVC 获取 web api 响应
【发布时间】:2017-12-25 19:09:30
【问题描述】:

我有一个 API 的 URL。我想在控制器中进行操作以获取所有数据

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。所以,我不知道为什么?

【问题讨论】:

  • 这对我来说很好用,你怎么调用这个方法?
  • 我在 js 文件中使用这个方法的路径...当我调试时我得到了 var json = null :/
  • 那为什么不让方法正确异步呢?不需要ContinueWith 的东西。
  • 那么,我该怎么办?
  • 我的意思是this

标签: asp.net-mvc api http asp.net-web-api


【解决方案1】:

您尝试在不使用异步的情况下执行异步代码。如果您使用正确的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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-04
    • 2019-01-18
    • 2016-12-20
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    相关资源
    最近更新 更多