【问题标题】:jQuery AJAX POST to ASMX web service results in "Cannot convert object of type System.String to System.Collections.Generic.IDictionary"jQuery AJAX POST 到 ASMX Web 服务导致“无法将 System.String 类型的对象转换为 System.Collections.Generic.IDictionary”
【发布时间】:2017-03-13 19:19:42
【问题描述】:

我有一个 ASMX Web 服务设置如下作为测试:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool Test (string id)
{
    if (id != null)
    {
        return true;
    }
    else
        return false;
}

然后我不会从 jQuery 调用该 Web 方法并传入参数“id”。所以我使用:

$.ajax({
    var data = JSON.stringify("id: 123");
    data: data,
    dataType: "json",
    url: url
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function (result) {},
    error: function (xmlHttpRequest, textStatus, errorThrown) {
          console.log(xmlHttpRequest.responseText);
          console.log(textStatus);
          console.log(errorThrown);
    }       
});

我使用JSON.stringify 来确保 JSON 是正确的。但是,当我运行上述内容时,我得到以下 500 Internal Server 错误:

{"Message":"无法将 \u0027System.String\u0027 类型的对象转换为 类型 \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":" 在 System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(对象 o, Type type, JavaScriptSerializer 序列化器, Boolean throwOnError, 对象\u0026 转换的对象)\r\n 在 System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(对象 o, Type type, JavaScriptSerializer 序列化器, Boolean throwOnError, 对象\u0026 转换的对象)\r\n 在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](字符串 输入)\r\n 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext 上下文,WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"} VM12798:89 错误

在我看来,一旦通过服务器收到请求,就会发生此错误。但是我不确定,为什么它试图将字符串变成IDictonary

上面的代码看起来很简单。我是否设置了错误的 JSON?如果我 console.log data 它返回:

"id: 123"

ASMX 是否期待一些不同的东西?

【问题讨论】:

  • 我想你想 JSON.stringify 一个对象,所以像: JSON.stringify({id: 123});
  • 将你的var声明移到对象的外部

标签: c# jquery json web-services


【解决方案1】:

您在 JSON 对象中声明 var data。直接设置data 属性即可。

另外,您错误地使用了JSON.stringify。它应该用于将 JavaScript 对象转换为 JSON 字符串。

查看下面的更新代码:

$.ajax({
        data: JSON.stringify({id: "123"}),
        dataType: "json",
        url: url
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (result) {},
        error: function (xmlHttpRequest, textStatus, errorThrown) {
              console.log(xmlHttpRequest.responseText);
              console.log(textStatus);
              console.log(errorThrown);
        }                   
});

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 2022-12-07
    • 1970-01-01
    • 2014-03-14
    • 2017-11-24
    • 2013-08-15
    • 1970-01-01
    • 2016-06-13
    • 2021-04-26
    相关资源
    最近更新 更多