Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly use HttpClient with async/await?

I'm getting two errors for the following code:

public async Task<string> TestDownloadTask()
{
    HttpResponseMessage response = null;

    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri(@"https://api.nasa.gov/planetary/apod");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        response.EnsureSuccessStatusCode();
        response = await client.GetStringAsync("?concept_tags=True&api_key=DEMO_KEY");
    }

    return response.Content;
}

I'm getting:

  • Cannot await 'System.Threading.Tasks.Task' on the "await" line
  • Cannot convert expression type 'System.Net.Http.Content' to return type 'string'

I've been attempting to write the above code that will download a string from a web service, but there seems to be a lot of conflicting information about how to use async and await and how to use HttpClient and I do not know what is wrong with the code I've written.

Where am I going wrong and how should I be doing it instead?

like image 892
user9993 Avatar asked Jun 28 '15 17:06

user9993


2 Answers

This method client.GetStringAsync returns Task<string>

public Task<string> TestDownloadTask()
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri(@"https://api.nasa.gov/planetary/apod");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // You don't need await here
        return client.GetStringAsync("?concept_tags=True&api_key=DEMO_KEY");
    }
}

To use above function:

public async void SomeMethod()
{
    // await to get string content
    string mystring = await TestDownloadTask();
}
like image 110
Nguyen Kien Avatar answered Nov 07 '22 19:11

Nguyen Kien


Change either to

return await client.GetStringAsync("?concept_tags=True&api_key=DEMO_KEY");

or to

return await response.Content.ReadAsStringAsync();
like image 41
nativehr Avatar answered Nov 07 '22 18:11

nativehr