Web Services Ajax调用Web服务-缺少参数错误

vkc1a9a2  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(132)

我试图从一个使用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()
wd2eg0qa

wd2eg0qa1#

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();
}

相关问题