以下代码出现两个错误:
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;
}
我得到:
- 无法在“await”行等待“System.Threading.Tasks.Task”
- 无法将表达式类型“System.Net.Http.Content”转换为返回类型“string”
我一直在尝试编写上面的代码来从网络服务下载字符串,但是关于如何使用 async 和 wait 以及如何使用 HttpClient 似乎有很多相互冲突的信息,我不知道我写的代码有什么问题。
我哪里出错了,我应该怎么做?
最佳答案
这个方法client.GetStringAsync
返回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");
}
}
使用上述功能:
public async void SomeMethod()
{
// await to get string content
string mystring = await TestDownloadTask();
}
关于c# - 如何正确使用 HttpClient 和 async/await?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31102741/