Roka545 Roka545 - 2 months ago 20
HTTP Question

Console.WriteLine after async await call.

I'm completely new to using async calls and await. I have the below unit test function:

public async static void POSTDataHttpContent(string jsonString, string webAddress)
{
HttpClient client = new HttpClient();
StringContent stringContent = new StringContent(jsonString);
HttpResponseMessage response = await client.PostAsync(
webAddress,
stringContent);

Console.WriteLine("response is: " + response);
}


The test completes without error, but I never see the Console.WriteLine print statement show up in output - I'm not sure why. I've been looking around and it sounds like I may need to set this up as a task? Could someone point me in the proper direction?

Answer

Since you are already awaiting an HttpResponseMessage, a simple (and consistent) solution is to return Task<HttpResponseMessage>.

var x = await POSTDataHttpContent("test", "http://api/");

public async Task<HttpResponseMessage> POSTDataHttpContent(
    string jsonString, string webAddress)
{
    using (HttpClient client = new HttpClient())
    {
        StringContent stringContent = new StringContent(jsonString);
        HttpResponseMessage response = await client.PostAsync(
        webAddress,
        stringContent);

        Console.WriteLine("response is: " + response);

        return response;
    }
}

That said, you also need to ensure that your test setup is correct. You cannot properly call an async method from a synchronous test. Instead, mark your test async as well and await the method you are calling. Furthermore, your test method must be marked as async Task as well since neither MS Test Runner nor other tools (NCrunch, NUnit) will properly deal with an async void test method:

[TestMethod]
public async Task TestAsyncHttpCall()
{
    var x = await POSTDataHttpContent("test", "http://api/");
    Assert.IsTrue(x.IsSuccessStatusCode);
}
Comments