ReactJS调用ASP.NET WebService的SignUp接口报500及JSON解析异常问题
问题根因
三个报错属于连锁触发关系:
- 核心问题是你用
application/json格式传递请求参数,但ASMX服务默认不会解析JSON请求体的内容。从错误堆栈的UrlParameterReader可以看出,服务端只识别URL参数或者表单格式参数,完全没有读取你放在请求体里的JSON内容,因此抛出Missing parameter : firstName异常,返回500错误。 - 500错误返回的是HTML格式的错误页面(而非你预期的XML/JSON格式),内容开头字符为
T(通常是错误页开头的"The server encountered an error..."类文本),因此JSON.parse执行失败,报第二个解析错误。
解决方案(两种可选,推荐第二种无需修改服务端代码)
方案1:服务端适配JSON请求
给WebService类添加ScriptService特性,让ASMX支持解析JSON请求体,同时调整前端解析逻辑适配JSON返回:
- 服务端代码修改:
// 给WebService类添加ScriptService注解 [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod] public string SignUp(string firstName, string lastName, string emailAddress, string password) { return BLL.SignUp(firstName, lastName, emailAddress, password); } }
- 前端fetch逻辑修改,去掉XML解析步骤直接读取JSON返回:
const signUp = (signUpData) => { let data = { firstName: signUpData.fName, lastName: signUpData.lName, emailAddress: signUpData.email, password: signUpData.password, }; fetch('http://localhost:50496/WebService.asmx/SignUp', { body: JSON.stringify(data), method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', }, }) .then((response) => response.json()) .then((userData) => { if (userData.d && userData.d.length > 0) { setUser(userData); } else { console.log('error no data'); } }) .catch((err) => { console.log(err); }); };
方案2:前端调整参数格式适配现有服务端(推荐)
你其他GET接口运行正常,说明服务端默认走表单/URL参数解析、XML返回的逻辑,只要把POST参数改成表单格式即可,无需修改任何服务端代码:
const signUp = (signUpData) => { // 构造表单格式参数 const formData = new URLSearchParams(); formData.append('firstName', signUpData.fName); formData.append('lastName', signUpData.lName); formData.append('emailAddress', signUpData.email); formData.append('password', signUpData.password); fetch('http://localhost:50496/WebService.asmx/SignUp', { body: formData, method: 'POST', headers: { // 改Content-Type为表单格式 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', }, }) // 原有XML解析逻辑保持不变即可 .then((response) => response.text()) .then( (xml) => new window.DOMParser().parseFromString(xml, 'text/xml') .documentElement.firstChild.textContent ) .then((jsonStr) => JSON.parse(jsonStr)) .then((userData) => { if (userData.d && userData.d.length > 0) { setUser(userData); } else { console.log('error no data'); } }) .catch((err) => { console.log(err); }); };
内容的提问来源于stack exchange,提问作者ExtraSun
相关产品推荐
相关产品推荐

