aaron
aaron

Reputation: 174

Asynchronous API call failing

I have two methods for making an API call. The first, cleverly named apiCall, works exactly as expected. I pass a string url, and object to post, the call is made, and I receive an HttpResponseMessage class object:

    public HttpResponseMessage apiCall(string url, object o)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.PostAsJsonAsync(url, o).Result;

            if (response.IsSuccessStatusCode)
            {
                return response;
            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
    }

However, I also have a method intended to make an asynchronous call. It is, very originally, named asyncApiCall, and is constructed as so:

public void asyncApiCall(string url, object o)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            client.PostAsJsonAsync(url, o);
        }
    }

As you can see, this is the same method, minus the code to actually return a response from the server. However, the server is not receiving any sort of message.

In summary: My synchronous calls are working, and my async calls are failing. I would imagine I'm doing something wrong, but all of the documentation I've been able to find implies the HttpClient's PostAsJsonAsync method is asynchronous by default. Logically, I would expect (and have seen many instances of people having) the opposite problem.

Upvotes: 0

Views: 1725

Answers (1)

David
David

Reputation: 219096

This needs to be awaited:

await client.PostAsJsonAsync(url, o);

Which means this needs to be async:

public async Task asyncApiCall(string url, object o)
{
    //...
}

Otherwise what's likely happening is that control is leaving the using block before the task actually executes, causing the task to fail. (since client is disposed.) And since the task is never awaited or examined, the failure isn't reported anywhere.

Upvotes: 5

Related Questions