Xamarin.Forms WebView无法打开localhost
1、新版的Android要求使用https,若要使用http,需要如下处理:
在“项目名.Android/Resources"下建立"xml"文件夹,在xml文件夹下创建一个network_security_config.xml文件,文件内容如下:
<?xml version="1.0" encoding="utf-8" ?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">10.0.2.2</domain> <!-- Debug port --> <domain includeSubdomains="true">xamarin.com</domain> </domain-config> </network-security-config>
在“项目名.Android/Properties/AndroidManifest.xml"中使用此配置,并启动访问网络的权限,内容如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.mphone"> <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" /> <application android:label="MPhone.Android" android:networkSecurityConfig="@xml/network_security_config"> </application> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> </manifest>
2、把你要访问的网站的解决方案下的.vs文件夹中的applicationhost.config加入127.0.0.1和*:
<bindings> <binding protocol="http" bindingInformation="*:61113:localhost" /> <binding protocol="http" bindingInformation="*:61113:127.0.0.1" /> <binding protocol="http" bindingInformation="*:61113:*" /> </bindings>
3、开启你的安卓模拟器的移动数据,关闭模拟器的Wifi,在移动网络配置的高级设置“Advance/AccessPointNames”中,使用默认的T-Mobile US
4、在安卓模拟器的右侧工具条的“…/Settings/Proxy”中,配置你的代理为“10.0.2.2”,端口号为您要访问的localhost网页的端口,比如这里的“61113”。
5、下面的代码不知是否需要(可能是需要的)
在WebView所在的页面的代码中加入(允许http):
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific; using Xamarin.Forms.PlatformConfiguration;
在您的webView中加入android:WebView.MixedContentMode="AlwaysAllow" 如下:
wvLogin.On<Android>().SetMixedContentMode(MixedContentHandling.AlwaysAllow);
<WebView x:Name="wvLogin" android:WebView.MixedContentMode="AlwaysAllow" Grid.RowSpan="5" IsVisible="False" HeightRequest="300" WidthRequest="500" BackgroundColor="LightBlue"/>
6、重启模拟器。
浙公网安备 33010602011771号