.NET 7.0与React Native通过Axios调用API失败问题求助
问题描述
我的.NET API在.NET 6.x版本下运行正常,但升级到.NET 7后出现异常:通过Thunder Client和Swagger可正常发起HTTP请求,但React Native(Expo)应用及Flutter调用均失败,使用Axios请求时出现以下错误:
Possible Unhandled Promise Rejection (id: 1):
相关配置与代码
- appsettings.json 配置
... "Kestrel": { "Endpoints": { "Http":{ "Url": "http://localhost:5000" }, "Https":{ "Url": "https://localhost:5001" } } }, ...
- Axios 请求代码
const baseUrl = 'https://localhost:5001/api/users'; const headers = { "Content-Type": "application/json", } const [user, setUser] = useState(null); useEffect(() => { axios.get(baseUrl, {headers}).then((response) => { setUser(response.data); console.log(response.data); }).catch(function(error){ console.log(error); console.log(error.response.data); }); }, []);
- Program.cs 中的CORS配置
... builder.Services.AddCors(options => { options.AddPolicy(name: CorsPolicy, policy => { policy.WithOrigins ( "exp://192.168.0.41:19000", "http://localhost:19006", "http://localhost:19000" ) .AllowAnyHeader() .AllowAnyMethod(); }); }); ... app.UseCors(CorsPolicy); ...
提问:这是.NET 7.0的问题还是巧合?该如何解决?
解决方案
这个问题并非巧合,主要和.NET 7对HTTPS证书验证、CORS预检请求的处理逻辑变化有关,以下是具体排查和解决步骤:
1. 先验证HTTPS证书问题
React Native/Flutter的真机/模拟器默认不会信任.NET 7生成的自签名HTTPS证书,而Thunder Client、Swagger运行在本地浏览器,已自动信任开发证书。
- 临时将请求改为HTTP(
http://localhost:5000/api/users)测试,若请求成功,可确认是HTTPS证书导致的问题。
2. 重新信任.NET 7开发证书
运行以下命令清理并重新安装信任开发证书:
dotnet dev-certs https --clean dotnet dev-certs https --trust
3. 补充CORS配置的凭据权限
.NET 7对CORS预检请求的校验更严格,当前配置缺少允许凭据的设置,需添加.AllowCredentials():
builder.Services.AddCors(options => { options.AddPolicy(name: CorsPolicy, policy => { policy.WithOrigins ( "exp://192.168.0.41:19000", "http://localhost:19006", "http://localhost:19000" ) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); // 新增该行 }); });
4. 完善Axios错误日志定位问题
当前catch块的错误输出不够详细,修改代码打印完整错误信息,精准定位问题:
.catch(function(error){ console.log('完整错误:', error); if (error.response) { console.log('响应状态:', error.response.status); console.log('响应数据:', error.response.data); } else if (error.request) { console.log('请求详情:', error.request); } else { console.log('错误原因:', error.message); } });
5. React Native平台额外配置(开发环境)
- iOS模拟器:在
Info.plist中添加允许HTTP明文请求的配置:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
- Android:在
AndroidManifest.xml的application标签内添加:
android:usesCleartextTraffic="true"
内容的提问来源于stack exchange,提问作者Isaac Cooke
相关产品推荐
相关产品推荐

