【发布时间】: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