我从这里采取了以下代码:http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client如何知道为什么HttpClient调用不返回?
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync>Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
我已经更新了BaseAddress和标题URL部分矿井。完整的URL通过浏览器按预期工作。
当我使用下面的代码时,调用是从Web API应用程序进行并返回的。我可以看到这一点,因为Web API应用程序正在调试模式下运行。但在这条线后,来电方没有任何反应:
HttpResponseMessage response = await client.GetAsync("api/products/1");
该应用似乎冻结。用户界面无响应。我确实在try/catch块中有这样的代码,但它没有遇到异常。
有没有办法找出发生了什么?
的应用程序被称为是这样的:
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
// TODO - Send HTTP requests
}
}
}
你如何调用执行此代码的方法?我会怀疑由于使用'.Wait()'或'.Result'造成的死锁。 –
你试过小提琴手吗? – Legends
我更新了OP – 4thSpace