从Windows商店应用程序调用Web Api

时间:2015-01-15 17:16:27

标签: c#

我有一个包含三个项目的解决方案。一个Windows应用商店,一个PCL和一个单元测试。

我试图调用我在localhost上运行的web-api。

在测试项目中它工作正常但是当我尝试从PCL运行相同的代码时,我得到以下异常:

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
                }
            }
        }

有没有人有类似的问题,知道解决方案? 谢谢!

0 个答案:

没有答案
相关问题