将数据从 jquery ajax 请求传递到 wcf 服务失败反序列化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/589520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing data from a jquery ajax request to a wcf service fails deserialization?
提问by Per Hornsh?j-Schierbeck
I use the following code to call a wcf service. If i call a (test) method that takes no parameters, but returns a string it works fine. If i add a parameter to my method i get a wierd error:
我使用以下代码调用 wcf 服务。如果我调用一个不带参数的(测试)方法,但返回一个字符串,它工作正常。如果我向我的方法添加一个参数,我会收到一个奇怪的错误:
{"ExceptionDetail":{"HelpLink":null,"InnerException":null,"Message":"The token '\"' was expected but found '''.","StackTrace":" at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)","Type":"System.Xml.XmlException"},"ExceptionType":"System.Xml.XmlException","Message":"The token '\"' was expected but found '''.","StackTrace":" at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\u000d\u000a at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"}
{"ExceptionDetail":{"HelpLink":null,"InnerException":null,"Message":"预期令牌 '\"' 但找到了 '''。","StackTrace":" 在 System.Xml.XmlExceptionHelper .ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a 在 System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\u000d\u000a 在 System.Runtime.Serialization .Json.XmlJsonReader.ParseStartElement()\u000d\u000a 在 System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a 在 System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyReader, Boolean parameters[Boolean parameters] isRequest)\u000d\u000a 在 System.ServiceModel.Dispatcher。DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a 在 System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] 参数, Boolean isRequest) \u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a在 System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a 在 System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message,Object[] 参数)\u000d\u000a 在 System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&Model rpc)\u000a.System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.Immutable.u000a at System.ServiceModel.Dispatcher.Immutable.u000a@Rpc\0Rpc0RMessages\u000d\u000a System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.RProcess(Boolean isOperationContextSet)","Type":"System.Xml.XmlException"},"ExceptionType":"System.Xml.XmlException","Message":"预期令牌'\"'但找到''' .","StackTrace":" 在 System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)\u000d\u000a 在 System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected) , Char found)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher .DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] 参数,Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher .DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\u000d\u000a at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter。 DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a at System.ServiceModel。Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\u000d\u000a 在 System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.Dispatcher.BepcMessageRu000a \u000d\u000a 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\u000d\u000d\u000d\u000d\u000d\u000d\u000d\u000d\u000dSystem. (MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&rpc)\u000d\u000a 在 System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"}
My jquery looks like this, but i tried changing the actual data which i send as a string serialized json (as you can see) to a pure json object with the same sad result.
我的 jquery 看起来像这样,但我尝试将作为字符串序列化 json(如您所见)发送的实际数据更改为具有相同结果的纯 json 对象。
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/Statistics.svc/Get7DaysStatistics",
dataType: "json",
data: "{'customerId': '2'}",
timeout: 10000,
success: function(obj) { updateStatistics(obj.d); },
error: function(xhr) {
if (xhr.responseText)
$("body").html(xhr.responseText);
else
alert('unknown error');
return;
}
});
The wcf service looks like this:
wcf 服务如下所示:
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), OperationContract]
public string Get7DaysStatistics(string customerId)
{
Debug.WriteLine(customerId);
return "Test done";
}
It's placed in a a class with the following attributes:
它被放置在具有以下属性的 aa 类中:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
I won't list the configuration in the web.config to keep this long message "short" but i can post it if anybody thinks they can use it - i just want to stress that i CAN call a method and get a result - string or even a json object i can read from as long as i DON'T pass any data to the wcf service.
我不会在 web.config 中列出配置以保持这个长消息“短”,但如果有人认为他们可以使用它,我可以发布它 - 我只想强调我可以调用一个方法并获得结果 - 字符串甚至我可以读取的 json 对象,只要我不将任何数据传递给 wcf 服务。
回答by Daniel Richardson
Use double quotes instead of single quotes in the JSON you are sending to the service. That is, change:
在您发送到服务的 JSON 中使用双引号而不是单引号。也就是说,改变:
data: "{'customerId': '2'}",
to
到
data: '{"customerId": "2"}',
I've tested this locally and this fixes the problem.
我已经在本地进行了测试,这解决了问题。
Incidentally, I debugged this using a method I've often used when calling ASMX and WCF services using libraries other than the built-in ASP.NET tools. I called the service using the client proxy created by an asp:ScriptReferenceand then inspected the request being sent to the server using an HTTP sniffer (such as HttpFoxfor FireFox) and compared the request to the one being sent by jQuery. Then you can usually quickly see what is different (and so probably wrong) with the request. In this case, it was clear that there was a difference in the POST data being sent.
顺便说一句,我使用一种在使用内置 ASP.NET 工具以外的库调用 ASMX 和 WCF 服务时经常使用的方法对此进行了调试。我使用由asp:ScriptReference创建的客户端代理调用该服务,然后使用 HTTP 嗅探器(例如HttpFoxfor FireFox)检查发送到服务器的请求,并将该请求与jQuery发送的请求进行比较。然后您通常可以快速查看请求的不同之处(因此可能是错误的)。在这种情况下,很明显发送的 POST 数据存在差异。
回答by Brian Paske
I have only ever thought that posting is essential for username and password log on functionality so this is the way I encode the JSon parameters I send to the web service...
我只认为发布对于用户名和密码登录功能是必不可少的,所以这是我对发送到 Web 服务的 JSon 参数进行编码的方式......
Here is the Webservice Contract..
这是Web服务合同..
[ServiceContract]
public interface ILogonService
{
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json
)]
string Logon(string un, string pw);
}
Here is the JQuery (Note the use of " and ' is important!)
这是 JQuery(注意“和”的使用很重要!)
$.ajax({
type: 'POST',
url: "/LogonService.svc/Logon",
data: '{ "un": "' + $('#un').val() + '", "pw": "' + $('#pw').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
回答by Paulo Silva
I did a function in jscript that solved the problem for sending data via POST to a WCF service ... follow the code ...
我在 jscript 中做了一个函数,它解决了通过 POST 将数据发送到 WCF 服务的问题......按照代码......
function formatJsonDataToWCFPost(d){
函数格式JsonDataToWCFPost(d){
var t = {};
var a = '{';
for (var j = 0; j < d.length; j++) {
var x = d[j];
for (var i in x) {
if (x.hasOwnProperty(i)) {
var c = j + 1 == d.length ? '}' : ',';
a += ('"' + i + '":"' + x[i] + '"' + c);
}
}
}
return a;
}
}
回答by davogones
I think on your operation you need this attribute:
我认为在你的操作中你需要这个属性:
[WebInvoke(Method="POST",
BodyStyle=WebMessageBodyStyle.Wrapped,
ResponseFormat=WebMessageFormat.Json
)]
See jQuery AJAX calls to a WCF REST Servicefor more info.
有关详细信息,请参阅对 WCF REST 服务的 jQuery AJAX 调用。