0

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

3
  • Do you see a different behavior if instead of setting a base address you do getasync on the whole url? Commented Apr 8, 2019 at 14:59
  • Hi @BugFinder, I have tried that to put the whole URL in GetAsync method and in the Uri method, but it doesn't make any difference. Commented Apr 8, 2019 at 15:02
  • Yes, you're using async incorrectly: Task.WaitAll blocks your request thread. Commented Apr 8, 2019 at 15:48

1 Answer 1

4

Do not block on async code; use async all the way:

public async Task<ActionResult> Index()
{
  await Developer();

  return View();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, have tried your solution and it works as expected. Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.