C# read from HttpResponseMessage

.net, c#, httpclient

Solution

You are creating an asynchronous task but not waiting for it to complete before returning. This means your `responseValue` never gets set.

To fix this, before your return do this:

task.Wait();

So your function now looks like this:

if (Method == HttpVerb.POST)
     response = client.PostAsync(domain, new StringContent(parameters)).Result;
else
     response = client.GetAsync(domain).Result;

if (response != null)
{
     var responseValue = string.Empty;

     Task task = response.Content.ReadAsStreamAsync().ContinueWith(t =>
     {
         var stream = t.Result;
         using (var reader = new StreamReader(stream))
         {
             responseValue = reader.ReadToEnd();
         }
     });

     task.Wait();

     return responseValue;
}

If you prefer to use `await` (which you possibly should), then you need to make the function this code is contained in `async`. So this:

public string GetStuffFromSomewhere()
{
    //Code above goes here

    task.Wait();
}

Becomes:

public async string GetStuffFromSomewhere()
{
    //Code above goes here

    await ...
}

Problem

I am using .net's Httpclient for the first time and finding it very hard. I have managed to call the server and receive response from it but stuck at reading from the response. Here is my code: ``` if (Method == HttpVerb.POST) response = client.PostAsync(domain, new StringContent(parameters)).Result; else response = client.GetAsync(domain).Result; if (response != null) { var responseValue = string.Empty; Task task = response.Content.ReadAsStreamAsync().ContinueWith(t => { var stream = t.Result; using (var reader = new StreamReader(stream)) { responseValue = reader.ReadToEnd(); } }); return responseValue; } ``` responseValue has {} in it although the service is returning data. How should I fix the issue? The project is in .Net 4.

Original source