android模拟器访问本地web应用,从 iOS 模拟器和 Android 模拟器连接到本地 Web 服务...
从 iOS 模拟器和 Android 模拟器连接到本地 Web 服务Connect to local web services from iOS simulators and Android emulators02/04/2021本文内容许多移动应用程序使用 Web 服务。Many mobile applications consume web services. 在开发阶段,在本地部署 Web
从 iOS 模拟器和 Android 模拟器连接到本地 Web 服务Connect to local web services from iOS simulators and Android emulators
02/04/2021
本文内容
许多移动应用程序使用 Web 服务。Many mobile applications consume web services. 在开发阶段,在本地部署 Web 服务和从 iOS 模拟器或 Android 模拟器中运行的移动应用程序中使用它是很常见的操作。During the development phase, it's common to deploy a web service locally and consume it from a mobile application running in the iOS simulator or Android emulator. 这可避免向托管的终结点部署 Web 服务并可直接进行调试体验,因为移动应用程序和 Web 服务都是在本地运行的。This avoids having to deploy the web service to a hosted endpoint, and enables a straightforward debugging experience because both the mobile application and web service are running locally.
在 iOS 模拟器或 Android 模拟器中运行的移动应用程序可以使用在本地运行并通过 HTTP 公开的 ASP.NET Core Web 服务,如下所示:Mobile applications running in the iOS simulator or Android emulator can consume ASP.NET Core web services that are running locally, and exposed over HTTP, as follows:
在 iOS 模拟器中运行的应用程序可以通过你的计算机 IP 地址或通过 localhost 主机名连接到本地 HTTP Web 服务。Applications running in the iOS simulator can connect to local HTTP web services via your machines IP address, or via the localhost hostname. 例如,对于通过 /api/todoitems/ 相对 URI 公开 GET 操作的本地 HTTP Web 服务,在 iOS 模拟器中运行的应用程序可以通过向 http://localhost:/api/todoitems/ 发送 GET 请求来使用操作。For example, given a local HTTP web service that exposes a GET operation via the /api/todoitems/ relative URI, an application running in the iOS simulator can consume the operation by sending a GET request to http://localhost:/api/todoitems/.
在 Android 模拟器中运行的应用程序可以通过 10.0.2.2 地址连接到本地 HTTP Web 服务,该地址是你的主机环回接口的别名(在开发计算机上为 127.0.0.1)。Applications running in the Android emulator can connect to local HTTP web services via the 10.0.2.2 address, which is an alias to your host loopback interface (127.0.0.1 on your development machine). 例如,对于通过 /api/todoitems/ 相对 URI 公开 GET 操作的本地 HTTP Web 服务,在 Android 模拟器中运行的应用程序可以通过向 http://10.0.2.2:/api/todoitems/ 发送 GET 请求来使用操作。For example, given a local HTTP web service that exposes a GET operation via the /api/todoitems/ relative URI, an application running in the Android emulator can consume the operation by sending a GET request to http://10.0.2.2:/api/todoitems/.
但是,若要使在 iOS 模拟器或 Android 模拟器上运行的应用程序能够使用通过 HTTP 公开的本地 Web 服务,还需要执行额外的步骤。However, additional work is necessary for an application running in the iOS simulator or Android emulator to consume a local web service that is exposed over HTTPS. 对于此方案,流程如下:For this scenario, the process is as follows:
在你的计算机上创建一个自签名的开发证书。Create a self-signed development certificate on your machine. 有关详细信息,请参阅创建开发证书。
配置项目,以便将合适的 HttpClient 网络堆栈用于调试版本。Configure your project to use the appropriate HttpClient network stack for your debug build. 有关详细信息,请参阅配置项目。For more information, see Configure your project.
指定本地计算机的地址。Specify the address of your local machine. 有关详细信息,请参阅指定本地计算机地址。
绕过本地开发证书安全检查。Bypass the local development certificate security check. 有关详细信息,请参阅绕过证书安全检查。
将依次讨论每项。Each item will be discussed in turn.
创建开发证书Create a development certificate
安装 .NET Core SDK 会将 ASP.NET Core HTTPS 开发证书安装到本地用户证书存储。Installing the .NET Core SDK installs the ASP.NET Core HTTPS development certificate to the local user certificate store. 但是,尽管证书已安装,但它不受信任。However, while the certificate has been installed, it's not trusted. 若要信任该证书,请执行以下一次性步骤,以运行 dotnet dev-certs 工具:To trust the certificate, perform the following one-time step to run the dotnet dev-certs tool:
dotnet dev-certs https --trust
下面的命令提供有关 dev-certs 工具的帮助:The following command provides help on the dev-certs tool:
dotnet dev-certs https --help
或者,当你运行使用 HTTPS 的 ASP.NET Core 2.1 项目(或更高版本)时,Visual Studio 将检测是否缺少开发证书并提供安装和信任。Alternatively, when you run an ASP.NET Core 2.1 project (or above), that uses HTTPS, Visual Studio will detect if the development certificate is missing and will offer to install it and trust it.
备注
ASP.NET Core HTTPS 开发证书是自签名证书。The ASP.NET Core HTTPS development certificate is self-signed.
有关在计算机上启用本地 HTTPS 的详细信息,请参阅启用本地 HTTPS。For more information about enabling local HTTPS on your machine, see Enable local HTTPS.
配置项目Configure your project
在 iOS 和 Android 上运行的 Xamarin 应用程序可以指定 HttpClient 类使用的是哪个网络堆栈,可选择托管网络堆栈或本机网络堆栈。Xamarin applications running on iOS and Android can specify which networking stack is used by the HttpClient class, with the choices being a managed network stack, or native network stacks. 托管堆栈提供与现有 .NET 代码的高级别兼容性,但限于 TLS 1.0 且速度可能更慢并导致更大的可执行文件大小。The managed stack provides a high level of compatibility with existing .NET code, but is limited to TLS 1.0 and can be slower and result in a larger executable size. 本机堆栈运行速度会更快且可以提供更高的安全性,但可能并不会提供 HttpClient 类的全部功能。The native stacks can be faster and provide better security, but may not provide all the functionality of the HttpClient class.
iOSiOS
在 iOS 上运行的 Xamarin 应用程序可以使用托管网络堆栈,或使用本机 CFNetwork 或 NSUrlSession 网络堆栈。Xamarin applications running on iOS can use the managed network stack, or the native CFNetwork or NSUrlSession network stacks. 默认情况下,新 iOS 平台项目使用 NSUrlSession 网络堆栈,以支持 TLS 1.2,并使用本机 API,以便提高性能并减小可执行文件大小。By default, new iOS platform projects use the NSUrlSession network stack, to support TLS 1.2, and use native APIs for better performance and smaller executable size.
AndroidAndroid
在 Android 上运行的 Xamarin 应用程序可以使用托管 HttpClient 网络堆栈,或使用本机 AndroidClientHandler 网络堆栈。Xamarin applications running on Android can use the managed HttpClient network stack, or the native AndroidClientHandler network stack. 默认情况下,新 Android 平台项目使用 AndroidClientHandler 网络堆栈,以支持 TLS 1.2,并使用本机 API,以便提高性能并减小可执行文件大小。By default, new Android platform projects use the AndroidClientHandler network stack, to support TLS 1.2, and use native APIs for better performance and smaller executable size.
指定本地计算机地址Specify the local machine address
iOS 模拟器和 Android 模拟器均提供对本地计算机上运行的安全 Web 服务的访问。The iOS simulator and Android emulator both provide access to secure web services running on your local machine. 但它们的本地计算机地址各不相同。However, the local machine address is different for each.
iOSiOS
iOS 模拟器使用主机网络。The iOS simulator uses the host machine network. 因此,在此模拟器中运行的应用程序可以通过计算机 IP 地址或通过 localhost 主机名连接到在本地计算机中运行的 Web 服务。Therefore, applications running in the simulator can connect to web services running on your local machine via the machines IP address or via the localhost hostname. 例如,对于通过 /api/todoitems/ 相对 URI 公开 GET 操作的本地安全 Web 服务,在 iOS 模拟器中运行的应用程序可以通过向 https://localhost:/api/todoitems/ 发送 GET 请求来使用操作。For example, given a local secure web service that exposes a GET operation via the /api/todoitems/ relative URI, an application running on the iOS simulator can consume the operation by sending a GET request to https://localhost:/api/todoitems/.
备注
从 Windows 运行 iOS 模拟器中的移动应用程序时,此应用程序将显示在用于 Windows 的远程 iOS 模拟器中。When running a mobile application in the iOS simulator from Windows, the application is displayed in the remoted iOS simulator for Windows. 但是,此应用程序会在配对的 Mac 上运行。However, the application is running on the paired Mac. 因此,在 Mac 上运行的 iOS应用程序无法对在 Windows 中运行的 Web 服务进行本地主机访问。Therefore, there's no localhost access to a web service running in Windows for an iOS application running on a Mac.
AndroidAndroid
Android模拟器的各个实例独立于开发计算机网络接口,在虚拟路由器的后方运行。Each instance of the Android emulator is isolated from your development machine network interfaces, and runs behind a virtual router. 因此,模拟设备无法看到开发计算机或网络中的其他模拟器实例。Therefore, an emulated device can't see your development machine or other emulator instances on the network.
但是,各个模拟器的虚拟路由器托管着一个包含预分配地址的特殊网络空间,其中 10.0.2.2 地址是主机环回接口的别名(在开发计算机上为 127.0.0.1)。However, the virtual router for each emulator manages a special network space that includes pre-allocated addresses, with the 10.0.2.2 address being an alias to your host loopback interface (127.0.0.1 on your development machine). 因此,对于通过 /api/todoitems/ 相对 URI 公开 GET 操作的本地安全 Web 服务,在 Android 模拟器中运行的应用程序可以通过向 https://10.0.2.2:/api/todoitems/ 发送 GET 请求来使用操作。Therefore, given a local secure web service that exposes a GET operation via the /api/todoitems/ relative URI, an application running on the Android emulator can consume the operation by sending a GET request to https://10.0.2.2:/api/todoitems/.
检测操作系统Detect the operating system
DeviceInfo 类可用于检测应用程序的运行平台。The DeviceInfo class can be used to detect the platform the application is running on. 可将支持访问本地安全 W eb 服务的相应主机名设置如下:The appropriate hostname, that enables access to local secure web services, can then be set as follows:
public static string BaseAddress =
DeviceInfo.Platform == DevicePlatform.Android ? "https://10.0.2.2:5001" : "https://localhost:5001";
public static string TodoItemsUrl = $"{BaseAddress}/api/todoitems/";
有关 DeviceInfo 类的详细信息,请参阅 Xamarin.Essentials:设备信息。For more information about the DeviceInfo class, see Xamarin.Essentials: Device Information.
绕过证书安全检查Bypass the certificate security check
如果试图从在 iOS 模拟器或 Android 模拟器中运行的应用程序调用本地安全 Web 服务,即使在各个平台上使用的是托管网络堆栈,也会引发 HttpRequestException。Attempting to invoke a local secure web service from an application running in the iOS simulator or Android emulator will result in a HttpRequestException being thrown, even when using the managed network stack on each platform. 因为本地 HTTPS 开发证书是自签名证书,而iOS 或 Android 不信任自签名证书。This is because the local HTTPS development certificate is self-signed, and self-signed certificates aren't trusted by iOS or Android. 因此,当应用程序使用本地安全 Web 服务时,需忽略 SSL 错误。Therefore, it's necessary to ignore SSL errors when an application consumes a local secure web service. 在 iOS 和 Android 上使用托管和本机网络堆栈时,这可以通过以下操作实现:将 HttpClientHandler 对象上的 ServerCertificateCustomValidationCallback 属性设置为忽略对本地 HTTPS 开发证书的证书安全检查结果的回调:This can be accomplished when using both the managed and native network stacks on iOS and Android, by setting the ServerCertificateCustomValidationCallback property on a HttpClientHandler object to a callback that ignores the result of the certificate security check for the local HTTPS development certificate:
// This method must be in a class in a platform project, even if
// the HttpClient object is constructed in a shared project.
public HttpClientHandler GetInsecureHandler()
{
HttpClientHandler handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
if (cert.Issuer.Equals("CN=localhost"))
return true;
return errors == System.Net.Security.SslPolicyErrors.None;
};
return handler;
}
在此代码示例中,如果待验证的证书不是 localhost 证书,会返回服务器证书验证结果。In this code example, the server certificate validation result is returned when the certificate that underwent validation is not the localhost certificate. 如果是此证书,将忽略验证结果,并返回 true,以指示证书有效。For this certificate, the validation result is ignored and true is returned, indicating that the certificate is valid. 生成的 HttpClientHandler 对象应作为参数传递到调试版本的 HttpClient 构造函数:The resulting HttpClientHandler object should be passed as an argument to the HttpClient constructor for debug builds:
#if DEBUG
HttpClientHandler insecureHandler = GetInsecureHandler();
HttpClient client = new HttpClient(insecureHandler);
#else
HttpClient client = new HttpClient();
#endif
启用 HTTP 明文流量Enable HTTP clear-text traffic
或者,可以将 iOS 和 Android 项目配置为允许明文 HTTP 流量。Optionally, you can configure your iOS and Android projects to allow clear-text HTTP traffic. 如果将后端服务配置为允许 HTTP 流量,则可以在基 URL 中指定 HTTP,然后将项目配置为允许明文流量:If the backend service is configured to allow HTTP traffic you can specify HTTP in the base URLs and then configure your projects to allow clear-text traffic:
public static string BaseAddress =
DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:5000" : "http://localhost:5000";
public static string TodoItemsUrl = $"{BaseAddress}/api/todoitems/";
iOS ATS 选择退出iOS ATS opt-out
若要在 iOS 上启用明文本地流量,应通过将以下内容添加到 Info.plist 文件来选择退出 ATS:To enable clear-text local traffic on iOS you should opt-out of ATS by adding the following to your Info.plist file:
NSAppTransportSecurity
NSAllowsLocalNetworking
Android 网络安全配置Android network security configuration
若要在 Android 上启用明文本地流量,应通过在 Resources/xml 文件夹中添加名为 network_security_config.xml 的新 XML 文件来创建网络安全配置。To enable clear-text local traffic on Android you should create a network security configuration by adding a new XML file named network_security_config.xml in the Resources/xml folder. XML 文件应指定以下配置:The XML file should specify the following configuration:
10.0.2.2
然后,在 Android 清单中的”应用程序”节点上配置 networkSecurityConfig 属性:Then, configure the networkSecurityConfig property on the application node in the Android Manifest:
...
相关链接Related links
更多推荐
所有评论(0)