-3

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

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

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

4

1 回答 1

0

尝试更改您的 api 操作以返回 a Task<IHttpActionResult>,然后 await 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);
 }

您也可以Task<string>从中返回Get,然后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;
 }
于 2017-03-22T20:11:04.780 回答