【发布时间】:2011-04-21 20:10:16
【问题描述】:
我有一个简单的 Web Service 方法定义为:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string MyWebMethod(string foo, string bar)
{
// DataContractJsonSerializer to deserialize foo and bar to
// their respective FooClass and BarClass objects.
return "{\"Message\":\"Everything is a-ok!\"}";
}
我将通过以下方式从客户端调用它:
var myParams = { "foo":{"name":"Bob Smith", "age":50},"bar":{"color":"blue","size":"large","quantity":2} };
$.ajax({
type: 'POST',
url: 'https://mydomain.com/WebServices/TestSvc.asmx/MyWebMethod',
data: JSON.stringify(myParams),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response, status) {
alert('Yay!');
},
error: function (xhr, err) {
alert('Boo-urns!');
}
});
但是,这会产生以下错误(MyWebMethod() 中第一行的断点永远不会被命中):
{"Message":"无参数 为类型定义的构造函数 \u0027System.String\u0027.","StackTrace":" 在 System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary
2 dictionary, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary2 rawParams)\r\n 在 System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext 上下文,WebServiceMethodData 方法数据,IDictionary`2 rawParams)\r\n 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext 上下文,WebServiceMethodData methodData)","ExceptionType":"System.MissingMethodException"}
我想传入两个字符串参数并使用 DataContractJsonSerializer 编写新的 Foo 和 Bar 对象。我错过了什么吗?
【问题讨论】:
-
对不起,我有点困惑。你在哪里传递两个字符串参数?看起来您只是传递了一个字符串参数,它是 myParams 中 JSON 值的字符串表示形式。还是 我 遗漏了什么? :)
-
由于参数是作为查询字符串值传递的,我假设:{ "queryString1":{}, "queryString2":{}}。我走远了吗?