Reputation: 3
I want to call the Web API through C# Task, but I am unable to get the returned result, although it does jump to the URL that I pointed out to get the values.
Do I implement the async and await method incorrectly?
Below is my code:
Web API with the route prefix of:
[RoutePrefix("api/values")]
The method is as below inside the Web API:
[Route("Developer")]
[HttpGet]
public Task<List<string>> Developer()
{
var developer = new List<string> { "Developer", "Developer" };
return Task.FromResult(developer);
}
Controller
private async Task<List<string>> Developer()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:52717/");
var response = await client.GetAsync("api/values/Developer");
if (response.IsSuccessStatusCode)
return new List<string>();
throw new Exception("Unable to get the values");
}
}
public ActionResult Index()
{
Task.WaitAll(Developer());
return View();
}
Whenever I launch the browser, it goes into the Index(), and goes to the Developer(), however, it keeps stuck and loading all the way up until the var response = await client.GetAsync("api/values/Developer")
gets called and goes through all the way to return Task.FromResult(developer);
, and it keeps stuck and loading all the way.
Anyone knows on how to make the Web API goes back to the caller?
Any help would be much appreciated.
Thanks
Upvotes: 0
Views: 788
Reputation: 456497
Do not block on async
code; use async
all the way:
public async Task<ActionResult> Index()
{
await Developer();
return View();
}
Upvotes: 4