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

React-Native连接ASP.NET Core Web API时出现网络错误求助

React-Native 连接 ASP.NET Core Web API 失败排查方案

问题描述

每次尝试将React-Native应用连接到ASP.NET Core Web API时均失败,已尝试将localhost替换为127.0.0.1:端口、使用Conveyor广播API,均无效。Postman测试Web API功能正常,但React-Native中调用始终失败。

前端测试代码(React-Native + Axios)

const testApiConnection = async () => {
    try {
      // 替换为实际的.NET Core API端点
      const apiUrl = 'https://192.168.1.80:45455/api/ApiCommuter/List';
  
      // 发起GET请求获取通勤者列表
      const response = await axios.get(apiUrl);
  
      if (response.status === 200) {
        const commuters = response.data;
  
        console.log('连接测试成功。');
        console.log('通勤者列表:', commuters);
      } else {
        console.log('连接测试失败:获取通勤者列表出错');
      }
    } catch (error) {
      console.log('连接测试失败。错误信息: ', error);
    }
  };

后端代码(ASP.NET Core)

控制器接口代码

[HttpGet("List")]
public async Task<ActionResult<IEnumerable<Commuter>>> GetCommuter()
{
    return await _context.Commuter.ToListAsync();
}

Startup.cs 配置代码

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using SecurityMonitoringSystem.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SecurityMonitoringSystem
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // 运行时调用,用于向容器添加服务
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(
                  Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>().AddDefaultTokenProviders()
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddCors();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowOrigin", builder =>
                {
                    builder.WithOrigins("http://localhost:8081", "https://your-react-native-app.com")
                           .AllowAnyHeader()
                           .AllowAnyMethod();
                });
            });
        }

        // 运行时调用,用于配置HTTP请求管道
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseDatabaseErrorPage();
                app.UseHttpsRedirection();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // 默认HSTS值为30天,生产环境可调整
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                     pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(
                    name: "generate",
                    pattern: "Drivers/Generate/{id}",
                    defaults: new { controller = "Drivers", action = "Generate" });
                            });
        }
    }
}

排查解决步骤

  • HTTPS证书信任问题:React-Native默认不信任开发环境的自签名SSL证书,临时解决可在axios请求中禁用SSL验证(仅开发环境使用):

    import https from 'https';
    
    const agent = new https.Agent({ rejectUnauthorized: false });
    const response = await axios.get(apiUrl, { httpsAgent: agent });
    

    长期方案是给测试设备安装ASP.NET Core的开发证书。

  • CORS配置优化:当前Startup中已添加全局CORS策略,但可尝试直接使用预定义的AllowOrigin策略替代临时定义,确保策略生效:

    // 替换原app.UseCors(...)为
    app.UseCors("AllowOrigin");
    
  • 网络连通性验证:

    1. 确保测试手机与运行API的电脑在同一局域网,通过手机ping 192.168.1.80确认网络可达;
    2. 修改API的launchSettings.json,将applicationUrl设置为https://0.0.0.0:45455;http://0.0.0.0:端口,允许API监听所有网卡地址。
  • 路由正确性检查:确认ApiCommuter控制器上添加了路由特性[Route("api/[controller]")],否则API端点路由会不匹配。

  • 错误详情排查:在前端catch块中打印更详细的错误信息,定位具体失败原因:

    console.log('错误详情:', error.response?.data, error.response?.status, error.message);
    

内容的提问来源于stack exchange,提问作者Norhassan M. Sarip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:58:15