从Android模拟器访问Dev Machine上的Localhost上的Webapi

时间:2017-02-05 03:57:44

标签: xamarin xamarin.android

这可能是一个重复的问题,但现有问题的答案都没有解决我的问题。

我的dev机器上运行了一个WebAPI端点。我已将其配置为在

上运行
.UseUrls("http://localhost:57971", "http://10.0.2.2:57971", "http://192.168.44.1:57971", "http://192.168.1.48:57971", "http://*:57971")

其中:

192.168.44.1 是仿真器网络设置标签上的桌面适配器#2

10.0.2.2 是Android模拟器的特殊地址,如Google的doco中所述(可能与Xamarin无关)和

192.168.1.48 是我的开发机器的本地IP地址。

我创建了一个允许TCP端口57971连接的防火墙规则。

我对此进行了大量研究,并注意到了http://briannoyesblog.azurewebsites.net/2016/03/06/calling-localhost-web-apis-from-visual-studio-android-emulator/

中列出的说明

我有点想法。令人讨厌的是,它无声地失败了。没有异常,输出只是基本上显示了用代码0退出的不同线程。并且应用程序继续运行,即调试会话没有将IDE返回到"代码条目" 州。这可能表明其他东西在这里发挥作用。

代码对我来说非常无害:

    protected async Task<T> GetAsync<T>(string url)
        where T : new()
    {
        HttpClient httpClient = CreateHttpClient();
        T result;

        try
        {
            var response = await httpClient.GetStringAsync(url);
            result = await Task.Run(() => JsonConvert.DeserializeObject<T>(response));
        }
        catch
        {
            result = new T();
        }

        return result;
    }

我正在使用Visual Studio 2015。 我正在使用Visual Studio模拟器https://www.visualstudio.com/vs/msft-android-emulator/

我知道如何在这件事情上获得轮子吗?

有没有办法从模拟器ping我的机器?

由于

1 个答案:

答案 0 :(得分:0)

我使用169.254.80.80进行了这项工作,即我将其添加到API所服务的网址列表中,并从Xamarin应用程序中调用该IP地址。

所以,在Program.cs中变得简单了:

.UseUrls("http://localhost:57971", "http://169.254.80.80:57971")

我还必须将它添加到ASP.NET API解决方案的隐藏 .vs 文件夹中的 bindings 元素 ApplicationConfig 文件中。不知道为什么它必须是169.254.80.80,因为那是桌面适配器#4。

这让它发挥作用。