新文章 网摘 文章 随笔 日记

Android emulator模拟器开发xamarin.forms,使用HttpClient无法访问所在Pc的Localhost Api服务(亲测有效)

原因:Visual Studio在IIS Express运行API,防火墙阻挡了模拟器访问IIS Express,LocalHost也不等于127.0.0.1,模拟器使用10.0.2.2代表所在的主机,但是是转换成127.0.0.1的,所以要解决问题,一要允许穿越防火墙,二要将127.0.0.1转换成Localhost。

解决方案:
假设API项目运行的网址是http://localhost:57980/
1、找到该项目所在解决方案的根目录文件夹,有一个.vs文件夹(是隐藏的,需要资源管理器设置允许查看隐藏的项目),打开.vs文件夹->config文件夹->applicationhost.config文件,

注意,里面可能有多个applicationhost.config,一定要找到有解决方案名称的文件夹下面的那个,例如下面要找到IdentityServer3.Sugar这个方案名里面的:

找到下面这一行:

<binding protocol="http" bindingInformation="*:57980:localhost" />

 

在其后添加下面两行:

<binding protocol="http" bindingInformation="*:57980:127.0.0.1" />
<binding protocol="http" bindingInformation="*:57980:*" />

 

即修改后变成如下的样子:

<binding protocol="http" bindingInformation="*:57980:localhost" />
<binding protocol="http" bindingInformation="*:57980:127.0.0.1" />
<binding protocol="http" bindingInformation="*:57980:*" />

其中第二行是使用127.0.0.1可访问,第三行是穿越防火墙

 

2、启动模拟器,在“…”配置->proxy->Manual proxy configgration->hostname

设置为10.0.2.2,PortNumber设置为PC主机后端API项目运行的端口号,本案例是57980。

 

3、Xamarin.Forms中的HttpClient请求的网址是http://10.0.2.2:57980,要与上面的配置一致。

 

4、保存后重新启动模拟器。经测试可以访问本机的API并得到了返回值。

posted @ 2020-08-19 12:09  岭南春  阅读(425)  评论(0)    收藏  举报