我花了一天的大部分时间研究这个问题,但我已经无计可施了。 我正在尝试使用 AJAX 从函数调用 Web 服务,但不断收到缺少参数的错误。
我添加了console.log()并且可以看到具有正确参数名称的数据。我希望有人能发现这个问题。
我在许多其他功能中使用相同的方法(即从 AJAX 调用 Web 服务方法)并且没有任何问题。我什至复制/粘贴了我知道正在运行的一个,只需更改 Web 服务方法名称(url)和传递的数据,同样的错误。
在 .asmx 中:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json]
public string ExportToExcel_TraceLog(string TLData)
{
string JSONresult = string.Empty;
do_whatever_with_TLData;
return JSONresult;
}
在 .aspx 中:
function exportToExcel() {
var jsonResult = JSON.stringify({ 'TLData': parseResults });
var url = '<%= ResolveUrl("../WebService/ABC.asmx/ExportToExcel_TraceLog") %>';
console.log(jsonResult);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
url: url,
data: JSON.stringify({ TLData: parseResults }), // I tried "data: jsonResult" too
}).done(function (result) {
// ...
}).fail(function (jqXHR, textStatus, errorThrown) {
});
}
这是我在浏览器中看到的对 console.log() 的响应,清楚地显示了参数 TLData
{"TLData":[{"RequestType":"d","NodeID":"E8","MessageLength":37,"Timestamp":"2023-07-25T07:47:03.566", ...}]},
}
这是我看到的错误:
System.InvalidOperationException: Missing parameter: TLData.
at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
ExportToExcel_TraceLog
正在尝试反序列化 json 对象,请尝试传递一个带双引号的字符串,并在 json 对象内转义:
function exportToExcel() {
var jsonResult = JSON.stringify(parseResults);
jsonResult = jsonResult.replaceAll("\"", "\\\"")
var url = '<%= ResolveUrl("../WebService/ABC.asmx/ExportToExcel_TraceLog") %>';
console.log(jsonResult);
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
url: url,
data: '{"TLData":"' + jsonResult + '"}'
}).done(function (result) {
// ...
}).fail(function (jqXHR, textStatus, errorThrown) {
});
}
然后你必须在 WebMethod 中再次反实现所有内容。
[HttpPost]
public string Post(JsonElement TLData)
{
//work with json data
return TLData.ToString();
}