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:
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?
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();
}
Change either to
return await client.GetStringAsync("?concept_tags=True&api_key=DEMO_KEY");
or to
return await response.Content.ReadAsStringAsync();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With