VS中USB连接实体安卓设备时MAUI应用无法连接ASP.NET Core Web API
解决.NET MAUI实体安卓设备访问本地ASP.NET Core API超时问题
以下是针对你遇到的实体设备API请求超时问题的分步解决方案:
1. 修正ASP.NET Core API的监听地址
默认情况下,ASP.NET Core API仅监听localhost,实体设备无法通过局域网访问。需要修改API的启动配置,使其监听所有网络接口:
- 打开API项目的
Properties/launchSettings.json,找到applicationUrl字段,修改为包含局域网IP或0.0.0.0:"applicationUrl": "http://0.0.0.0:5137;http://localhost:5137" - 或者通过命令行启动API时指定监听地址:
dotnet run --urls=http://0.0.0.0:5137
2. 配置Windows防火墙允许API端口访问
Windows防火墙默认会阻止外部设备访问本地端口,需添加入站规则:
- 打开「Windows Defender防火墙」→「高级设置」→「入站规则」→「新建规则」
- 规则类型选择「端口」,下一步后输入
5137,选择「TCP」协议 - 选择「允许连接」,根据你的网络环境勾选「域」「专用」「公网」选项
- 为规则命名(比如「Allow API Port 5137」)并完成配置
3. 确保设备与电脑在同一网络
实体安卓设备必须和运行API的电脑处于同一局域网:
- 关闭设备的移动数据,连接到电脑所在的WiFi网络
- 若无WiFi,可开启电脑的移动热点,让设备连接该热点
4. 修正MAUI中的BaseUrl配置
10.0.2.2是安卓模拟器专属的回环地址,实体设备无法使用,需替换为电脑的局域网IP:
public static string BaseUrl = DeviceInfo.Platform switch { DevicePlatform.Android => "http://192.168.0.22:5137/api", // 替换为你的电脑局域网IPv4地址 _ => "http://localhost:5137/api" };
- 可在电脑命令行执行
ipconfig查看自身的局域网IPv4地址
5. 验证网络连通性
在实体设备的浏览器中直接访问API接口,确认网络可达:
- 输入地址:
http://192.168.0.22:5137/api/[你的接口路径] - 若能正常返回数据,说明网络问题已解决;若无法访问,回到前几步检查配置
6. 检查HttpClient的请求代码
确保你正确拼接了请求地址:
- 未设置
HttpClient.BaseAddress时,PostAsync需传入完整接口地址:HttpResponseMessage responseMessage = await httpClient.PostAsync($"{BaseUrl}/your-endpoint", content); - 若提前设置
BaseAddress,可简化请求路径:httpClient.BaseAddress = new Uri(BaseUrl); HttpResponseMessage responseMessage = await httpClient.PostAsync("your-endpoint", content);
7. 确认安卓网络安全配置
确保network_security_config.xml允许向电脑IP发送明文HTTP请求:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">192.168.0.22</domain> <!-- 你的电脑IP --> <domain includeSubdomains="true">localhost</domain> <!-- 兼容模拟器 --> </domain-config> </network-security-config>
并在AndroidManifest.xml中引用该配置:
<application android:networkSecurityConfig="@xml/network_security_config" ...>
内容的提问来源于stack exchange,提问作者Sam Jones
相关产品推荐
相关产品推荐

