Q:

ASP.NET HTTPClient Get request status waiting for activation

I am writing a method that will return JSON data by making a GET request to a RestApi URL. When I run the application in debug mode, I get below data in response.
Id = 337, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
Here is my code:
public class Methods
{
    public static async Task<JObject> Get(string url, string username, string password)
    {
        var credentials = new NetworkCredential(username, password);
        HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
        HttpClient client = new HttpClient(handler);
        // client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            return JObject.Parse(await response.Content.ReadAsStringAsync());
        }
        return new JObject { response.StatusCode };
    }
}

Here is my view where I am trying to access data:
public IActionResult Index()
{
    // Methods RestMethod = new Methods();
    var data = Methods.Get("http://url/products", "domain\userid", "Password");

    return View();
}

When I add debug in view at var data = ..... thats where I am getting waiting for activation.
Any help is really appreciated. :)
Thanks,
Ray

A:

If you are going to use async/await you should do it starting from the calling entry point. Currently you call the Get method which returns a running task but you do not wait for it to be completed. The easiest fix is for your Index method code should be changed like so:
public async Task<IActionResult> Index()
{
    // Methods RestMethod = new Methods();
    var data = await Methods.Get("http://url/products", "domain\userid", "Password");
    return View();
}

Also see Stephen Cleary's blog for more details on async/await, he has written extensively on on this subject and also well known pitfalls and patterns.

