You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android平板端MAUI应用无法连接本地ASP.NET Web API

问题

我在本地机器上运行着一个ASP.NET Web API,在PC上通过http://localhost:5169/api可以正常访问,但用Android平板上的MAUI应用通过http://192.168.xx.xxx:5169/api访问时却无法连接。

已执行的操作:

  • 在PC防火墙中添加入站规则,开放5169端口;
  • 在Program.cs文件中配置CORS以允许跨域调用;
  • 在AndroidManifest.xml中添加网络安全配置以允许明文流量,配置内容如下:
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

调试时,MAUI应用的API调用仅抛出无响应码的异常,ASP.NET Web API端无日志生成。该URI在Postman中可正常使用,但平板上不行。目前处于开发阶段,暂不想部署应用,需要本地开发的解决方案。

想问还有哪些排查方向?是否是网络安全配置或其他问题导致的?

排查方向与解决方案

1. 修正Android网络安全配置

你当前的配置仅允许10.0.2.2的明文流量,但实际访问的是192.168.xx.xxx,平板会拦截该请求。修改配置添加你的PC局域网IP:

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
        <domain includeSubdomains="true">192.168.xx.xxx</domain>
    </domain-config>
</network-security-config>

开发阶段也可直接允许所有明文流量(仅用于开发):

<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

2. 确认ASP.NET Web API的监听地址

默认情况下,ASP.NET Core可能仅监听localhost,导致局域网设备无法访问。修改API启动配置使其监听所有网卡:

  • 在Program.cs中配置Kestrel:
var builder = WebApplication.CreateBuilder(args);
// 其他配置
builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenAnyIP(5169); // 监听所有IP的5169端口
});
  • 或在launchSettings.json中修改applicationUrl为http://0.0.0.0:5169。

3. 验证网络连通性

  • 在平板浏览器中直接访问http://192.168.xx.xxx:5169/api,若浏览器也无法访问,说明问题出在网络或API配置,而非MAUI应用。
  • 分别在PC和平板上互相ping对方IP,确认同一局域网内连通正常,检查是否存在WiFi频段隔离(如PC连2.4G、平板连5G且路由器隔离了频段)。

4. 检查MAUI应用网络权限

确保AndroidManifest.xml已添加必要权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

5. 排查防火墙与安全工具

  • 除Windows防火墙外,关闭PC上的第三方杀毒软件或安全工具,确认它们未拦截入站请求。
  • 检查防火墙入站规则:协议为TCP,端口5169,允许范围为192.168.0.0/16这类局域网段,而非仅特定IP。

6. 确认CORS配置生效

检查CORS配置是否正确,且中间件顺序正确:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

// 中间件顺序:放在UseRouting之后,UseAuthorization之前
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();
// 其他中间件

内容的提问来源于stack exchange,提问作者Dragon Slayer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:43:19