【问题标题】:getting stuck after sending async request to node.js server向 node.js 服务器发送异步请求后卡住
【发布时间】:2017-08-15 03:26:54
【问题描述】:

我已经在控制台应用程序中尝试过

public async Task<string> Getsmth(string a, string b, string c, HttpClient client)
{
string str = "call to node.js"
var response = await client.GetStringAsync(str);
return response;
}

在控制台应用程序中调用它效果很好,但是在 web api 中调用相同的代码后它卡在等待行

[Route("api/Getsmth/{a}/{b}/{c}")]
public string Get(string a, string b, string c)
{
 HttpClient client = new HttpClient();
 var r = Getsmth(a, b, c, client);
return r.Result;
}

在同步调用它之后(没有 async/await)一切正常。似乎是什么问题?!如何让它异步工作?

【问题讨论】:

  • 当你说你调用它没有 async/await 时,你还在返回一个任务吗?

标签: c# asp.net-web-api async-await sendasynchronousrequest


【解决方案1】:

尝试更改您的 api 操作以返回 Task&lt;IHttpActionResult&gt;,然后等待 Getsmth,如下所示:

[Route("api/Getsmth/{a}/{b}/{c}")]
public async Task<IHttpActionResult> Get(string a, string b, string c)
{
   HttpClient client = new HttpClient();
   var r = await Getsmth(a, b, c, client);
   return Ok(r);
 }

您也可以从Get 返回Task&lt;string&gt;,然后只返回return r 而不是Ok(r)

[Route("api/Getsmth/{a}/{b}/{c}")]
public async Task<string> Get(string a, string b, string c)
{
   HttpClient client = new HttpClient();
   var r = await Getsmth(a, b, c, client);
   return r;
 }

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2019-03-16
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 2012-12-20
    • 1970-01-01
    相关资源
    最近更新 更多