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

MAUI Android/iOS调用Web API时出现空引用异常求助

解决MAUI Android/iOS调用IIS Web API的空引用异常

问题核心分析

从代码和配置来看,空引用异常来自两个关键层面:

  1. 客户端逻辑漏洞:请求失败时未判空就直接访问对象属性
  2. 移动端网络与域名解析问题:安卓/iOS无法识别webapicd主机名,且网络安全配置未匹配请求域名

分步解决方案

1. 修复客户端空引用逻辑

原代码中,无论API请求是否成功,都直接访问Cds1.CdNom,当请求失败时Cds1保持为null,必然触发空引用异常。修改代码如下:

static async Task LectureAsync2()
{
    client.BaseAddress = new Uri("http://10.1.0.10:7134/"); // 改用服务器IP替代主机名,避免解析问题

    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    try
    {
        Console.WriteLine("GET 1 Cd");
        fich Cds1 = null;
        HttpResponseMessage response = await client.GetAsync("api/Cds/11"); // 利用BaseAddress简化请求路径

        if (response.IsSuccessStatusCode)
        {
            Cds1 = await response.Content.ReadAsAsync<fich>();
            // 仅在对象非空时访问属性
            if (Cds1 != null)
            {
                Console.WriteLine(Cds1.CdNom);
            }
            else
            {
                Console.WriteLine("未获取到有效CD数据");
            }
        }
        else
        {
            Console.WriteLine($"请求失败:{response.StatusCode}");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine($"异常信息:{e.Message}\n{e.StackTrace}"); // 打印完整栈信息便于深层排查
    }

    Console.ReadLine();
}

2. 修复安卓网络安全配置

当前网络安全配置仅允许10.1.0.10的明文流量,但原请求使用webapicd域名,安卓会拦截该明文请求。修改network_security_config.xml:

<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">10.1.0.10</domain>
    <domain includeSubdomains="true">webapicd</domain> <!-- 添加主机名,匹配请求域名 -->
  </domain-config>
</network-security-config>

3. 解决移动端域名解析问题

Windows可能通过本地hosts文件配置了webapicd对应10.1.0.10,但移动端设备无此配置,导致无法解析主机名。二选一解决:

  • 直接使用服务器IP:如上述客户端代码修改,用http://10.1.0.10:7134替代webapicd,彻底避免解析问题
  • 配置DNS映射:确保移动端所在网络的DNS服务器能解析webapicd,或安卓设备root后手动修改hosts文件添加映射

4. iOS额外ATS配置

iOS默认阻止明文HTTP请求,需在Info.plist中添加ATS例外:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>10.1.0.10</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>webapicd</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

验证步骤

  1. 确保IIS服务器的Web API能通过http://10.1.0.10:7134/api/Cds/11正常访问
  2. 移动端设备与服务器处于同一局域网
  3. 重新部署MAUI应用到安卓/iOS设备,测试API调用

内容的提问来源于stack exchange,提问作者eric pregnon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:25:41