【发布时间】:2012-11-04 21:15:24
【问题描述】:
我在 .Net Framework 4.5 上运行的 ASP.Net MVC 4 Web Api 项目中使用 HttpClient 调用外部服务
示例代码如下(忽略返回值,这是测试调用外部服务的示例代码):
public class ValuesController : ApiController
{
static string _address = "http://api.worldbank.org/countries?format=json";
private string result;
// GET api/values
public IEnumerable<string> Get()
{
GetResponse();
return new string[] { result, "value2" };
}
private async void GetResponse()
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(_address);
response.EnsureSuccessStatusCode();
result = await response.Content.ReadAsStringAsync();
}
}
虽然私有方法中的代码确实有效,但我遇到的问题是控制器 Get() 调用 GetResponse() 但它不等待结果,而是立即执行返回结果 = null。
我还尝试过使用 WebClient 进行更简单的同步调用,如下所示:
// GET api/values
public IEnumerable<string> Get()
{
//GetResponse();
var client = new WebClient();
result = client.DownloadString(_address);
return new string[] { result, "value2" };
}
效果很好。
我做错了什么?为什么 Get() 不等待异步示例中的私有方法完成?
【问题讨论】:
-
你不需要用 await 调用 GetResponse() 吗?否则,这不会等待该方法完成......并且您的控制器操作将直接完成,结果仍然为空。
-
是的,但我没有意识到我可以将 Get() 标记为异步,这是使用 await 所必需的。
标签: c# asp.net-web-api dotnet-httpclient