C# 从windows应用商店应用程序调用webApi
我有一个包含三个项目的解决方案。一个windows应用商店应用程序、一个PCL和一个单元测试 我试图调用我在本地主机上运行的web api 在测试项目中,它工作正常,但当我尝试从PCL运行相同的代码时,我得到以下异常:C# 从windows应用商店应用程序调用webApi,c#,C#,我有一个包含三个项目的解决方案。一个windows应用商店应用程序、一个PCL和一个单元测试 我试图调用我在本地主机上运行的web api 在测试项目中,它工作正常,但当我尝试从PCL运行相同的代码时,我得到以下异常: A connection attempt failed because the connected party did not properly respond after a period of time or established connection failed bec
A connection attempt failed because the connected party did not properly respond after a period of time or established connection failed because connected host has failed to respond 127.0.0.1:12345
我还尝试添加一个控制台应用程序并运行sam代码,结果成功了。关于windows应用商店应用程序,我肯定缺少一些内容
下面是我用来调用API的代码:
public async void CallMyApi()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:12345/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = client.GetAsync("api/user/16").Result;
if (response.IsSuccessStatusCode)
{
//success
}
}
catch (Exception ex)
{
//fail
}
}
}
有没有人遇到过类似的问题并知道解决方案?
谢谢 你确定你的服务正在运行吗?使用GetAsync.Result而不是Wait GetAsync的具体原因是什么?请注意,异步方法应该返回任务。感谢您的回答。是的,我肯定服务正在运行。我还尝试将GetAsync.Result更改为等待GetAsync。同样的结果。我不明白它如何在控制台应用程序或作为单元测试中工作……我还可以补充一点,当我在本地主机上运行WebApi时,与windows应用商店应用程序同时运行,它们在不同的解决方案中,WebApi中的方法永远不会被击中……另一个有趣的事情是,只有在本地主机上运行WebApi时,才会出现此问题。当我把它放在网上时,它就如预期的那样工作了。。