C# read from HttpResponseMessage

15,458

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 ...
}
Share:
15,458
Haris
Author by

Haris

Updated on June 04, 2022

Comments

  • Haris
    Haris almost 2 years

    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.

    • PrinceT
      PrinceT almost 10 years
      you are using wcf service or web service? What is the status of reponse? responseValue.StatusCode = ?
    • DavidG
      DavidG almost 10 years
      Shouldn't you be awaiting task before returning?
    • Haris
      Haris almost 10 years
      @PrinceT I am calling rest service
    • Haris
      Haris almost 10 years
      @DavidG where should I use await? well where ever I put await VS shows error that The await operator can only be used within an async method
    • DavidG
      DavidG almost 10 years
      @Haris As your function is not async, just use Task.Wait(), check my answer.
  • DavidG
    DavidG almost 10 years
    WebRequest should not be used when the newer HttpClient is available. Also, this doesn't answer the question being asked.
  • Haris
    Haris almost 10 years
    nope still the same :(. however it works perfectly fine with WebRequest but the problem due to which I had to move to HttpClient was that with WebRequest I was unable to read cookies.
  • Haris
    Haris almost 10 years
    I was previously using WebRequest but I could not read cookies that is why moved to HttpClient. otherwise WebRequest works perfectly.
  • DavidG
    DavidG almost 10 years
    Is the function in the ContinueWith being executed?
  • Haris
    Haris almost 10 years
    yes it is being executed. noticed that t.Result.Length has 2 in it
  • DavidG
    DavidG almost 10 years
    I recommend reading this article to see how to use HttpClient: asp.net/web-api/overview/web-api-clients/…
  • Haris
    Haris almost 10 years
    ok I got the data by changing domain and parameters. Domain was changed from http://mydomain.com:38080/workshop/ to http://mydomain.com:38080/workshop/rest/login and parameters was changed from to rest/login?username=usr&password=pwd to username=usr&password=pwd. why is that? this will create problem of getting cookies as they are set at the domain level
  • DavidG
    DavidG almost 10 years
    Ah I see now. Well my answer still applies even though it's not a solution for you.
  • Haris
    Haris almost 10 years
    this means that I have to give complete address to rest controller. How will it affect the cookies (from where all this started). Because now when I get cookie from mydomain.com:38080/workshop I do not get anything