React Native与ASP.NET WebService通信失败问题求助
React Native 与 ASP.NET ASMX WebService 通信问题解决方案
核心错误分析
错误信息Failed to connect to localhost/127.0.0.1:44358的核心原因是:React Native模拟器/设备的localhost指向自身,而非运行ASMX服务的电脑,导致无法建立网络连接。此外还需排查SOAP请求格式、CORS配置及ASMX服务的可用性。
具体解决步骤
1. 替换请求URL为电脑局域网IP
- 将React Native中的请求地址从
http://localhost:44358/BikeWebService.asmx改为运行ASMX服务的电脑局域网IP地址(例如http://192.168.3.10:44358/BikeWebService.asmx)。 - 确保ASMX服务绑定到局域网IP而非仅
127.0.0.1:- 若使用IIS Express,修改项目根目录下
.vs/config/applicationhost.config,将站点绑定的bindingInformation从*:44358:localhost改为*:44358:(空主机头)或*:44358:[局域网IP]。 - 若使用本地IIS,在站点绑定中添加局域网IP的端口绑定。
- 若使用IIS Express,修改项目根目录下
2. 修正ASMX的CORS配置(ASP.NET 4.8)
ASMX默认不处理跨域预检的OPTIONS请求,需手动配置:
- 在
web.config中添加跨域响应头:<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Methods" value="POST, OPTIONS" /> <add name="Access-Control-Allow-Headers" value="Content-Type, SOAPAction" /> </customHeaders> </httpProtocol> </system.webServer> - 在
Global.asax中添加OPTIONS请求处理逻辑,避免ASMX返回404:protected void Application_BeginRequest(object sender, EventArgs e) { if (Request.HttpMethod.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase)) { Response.StatusCode = 200; Response.End(); } }
3. 验证并修正SOAP请求格式
从WCF测试客户端获取的XML格式本身是正确的,但需注意React Native中的字符串处理:
- 避免手动转义XML字符,使用ES6模板字符串简化拼接,保证格式正确:
const sr = ` <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/LogIn</Action> </s:Header> <s:Body> <LogIn xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/"> <password>a</password> <login>1</login> </LogIn> </s:Body> </s:Envelope> `.trim(); - 确保请求头包含
SOAPAction,ASMX依赖该头确定调用的WebMethod:// XMLHttpRequest方式 xmlhttp.setRequestHeader('SOAPAction', 'http://tempuri.org/LogIn'); // Axios方式 axios.post(url, sr, { headers: { 'Content-Type': 'text/xml', 'SOAPAction': 'http://tempuri.org/LogIn' } })
4. 排查网络与服务可用性
- 在模拟器/设备的浏览器中访问
http://[电脑IP]:44358/BikeWebService.asmx,确认能打开ASMX服务页面,排除网络连通问题。 - 用Postman发送SOAP请求测试ASMX服务本身是否正常响应,排除服务端逻辑错误。
5. 调整React Native请求配置
- 若无需身份验证,去掉
withCredentials: true,避免跨域凭证冲突。 - 增加超时配置,避免因网络延迟导致请求失败。
关于WCF测试客户端XML的正确性
从WCF测试客户端获取的XML格式是正确的,需注意:
- SOAP Envelope命名空间、Action头与WebMethod的命名空间(默认
http://tempuri.org/)一致。 - 参数元素名与WebMethod的参数名完全匹配(ASMX按元素名匹配参数,与顺序无关)。
内容的提问来源于stack exchange,提问作者Mariusz
相关产品推荐
相关产品推荐

