Xamarin:连接到本地托管的 Web 服务 [英] Xamarin: Connect to locally hosted web service

查看:25
本文介绍了Xamarin:连接到本地托管的 Web 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 web api 应用程序来连接 xamarin 和 android.
我已经尝试了很多,但会出现一些连接错误.

I want to create a web api application to connect xamarin with android.
I had tried a lot, but some connection errors are coming.

我的代码如下:

public async Task<JsonValue> find(int ID)
    {
     using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:49836");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage result = client.GetAsync("api/Product").Result;
           return JsonConvert.DeserializeObject<JsonValue>(await result.Content.ReadAsStringAsync());                
     }       
    }
    }

我收到如下错误

System.Net.WebException:错误:ConnectFailure(连接被拒绝)---> System.Net.Sockets.SocketException:连接被拒绝

System.Net.WebException: Error: ConnectFailure (Connection refused) ---> System.Net.Sockets.SocketException: Connection refused

谁能帮忙.任何帮助表示赞赏.

Can any one help. Any help is appreciated.

推荐答案

如果您使用的是 Android 模拟器,那么请求 localhost Web 服务将不起作用,因为您正在查看模拟器的 localhost.你怎么能解决这个问题?好吧,Android Emulator 有一个神奇的地址 http://10.0.2.2:your_port 指向 127.0.0.1:your_port在您的主机上.查看此处.因为它指向的是 IP 而不是本地主机,所以您需要进入您的项目解决方案,在 .vs 文件夹->config->applicationhost.config 中并更改此 进入,这里13142是我的端口,你的可能不一样.重新启动 IIS Express,一切顺利.

If you're using an Android Emulator then asking for the localhost web service won't work, because you're looking at the localhost of the emulator. How can you fix this? Well, Android Emulator has a magic address http://10.0.2.2:your_port that points to 127.0.0.1:your_port on your host machine.Take a look here. Because it points to an IP and not localhost, you need to go into your project solution, in .vs folder->config->applicationhost.config and change this <binding protocol="http" bindingInformation="*:13142:localhost" /> into <binding protocol="http" bindingInformation="*:13142:127.0.0.1" />, where 13142 is my port, yours may be different. Restart IIS Express and you're good to go.

这篇关于Xamarin:连接到本地托管的 Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆