-3

I have tried it in console application

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

calling it in console application worked greatly, but after calling same code in web api it got stuck in await line

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

after calling it synchronously (without async/await) everything works fine. what seems to be the problem?! How to make it work asynchronously?

1 Answers1

0

Try changing your api action to return a Task<IHttpActionResult>, then await Getsmth, like this:

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

You could return Task<string> from Get as well, then just return r instead instead of 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;
 }
Mike_G
  • 16,237
  • 14
  • 70
  • 101