简体   繁体   English

将数据从jquery ajax请求传递到wcf服务失败反序列化?

[英]Passing data from a jquery ajax request to a wcf service fails deserialization?

I use the following code to call a wcf service. 我使用以下代码来调用wcf服务。 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: 如果我向我的方法添加一个参数我得到一个奇怪的错误:

{"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)\ \ at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\ \ at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\ \ at System.Runtime.Serialization.Json.XmlJsonReader.Read()\ \ at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] parameters, Boolean isRequest)\ \ at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\ \ at System.ServiceModel.D {“ExceptionDetail”:{“HelpLink”:null,“InnerException”:null,“Message”:“令牌'\\”'是预期的但是找到'''。“,”StackTrace“:”在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 System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader,Object []参数,布尔的System.Runtime.Serialization.Json.XmlJsonReader.Read()\\ u000d \\ u000a的.Json.XmlJsonReader.ParseStartElement()\\ u000d \\ u000a isRequest)\\ u000d \\ u000a在System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader,MessageVersion version,String action,MessageDescription messageDescription,Object [] parameters,Boolean isRequest)\\ u000d \\ u000a at System.ServiceModel.D ispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\ \ at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\ \ at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\ \ at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\ \ at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\ \ at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.Immutabl System.ServiceModel.Dispatcher上的System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(消息消息,Object []参数)\\ u000d \\ u000a中的ispatcher.OperationFormatter.DeserializeBodyContents(消息消息,Object []参数,布尔isRequest)\\ u000d \\ u000a .DemultiplexingDispatchMessageFormatter.DeserializeRequest(消息消息,Object []参数)\\ u000d \\ u000a在System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(消息消息,Object []参数)\\ u000d \\ u000a at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest (消息消息,对象[]参数)\\ u000d \\ u000a在System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc&rpc)\\ u000d \\ u000a at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&rpc)\\ u000d \\ u000a at at System.ServiceModel.Dispatcher.Immutabl中的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&rpc)\\ u000d \\ u000a eDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\ \ 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)\ \ at System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader, String expected, Char found)\ \ at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\ \ at System.Runtime.Serialization.Json.XmlJsonReade System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&rpc)\\ u000d \\ u000a的eDispatchRuntime.ProcessMessage4(MessageRpc&rpc)\\ u000d \\ u000a位于System的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&rpc)\\ u000d \\ u000a。 Service.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&rpc)\\ u000d \\ u000a at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)“,”Type“:”System.Xml.XmlException“},”ExceptionType“:”System .Xml.XmlException“,”消息“:”令牌'\\“'是预期的但是找到'''。”,“StackTrace”:“在System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader,String res,String arg1,字符串arg2,字符串arg3)\\ u000d \\ u000a在System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader reader,String expected,Char found)\\ u000d \\ u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\\ u000d \\ u000a在System.Runtime.Serialization.Json.XmlJsonReade r.Read()\ \ at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBodyCore(XmlDictionaryReader reader, Object[] parameters, Boolean isRequest)\ \ at System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)\ \ at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)\ \ at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)\ \ at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)\ \ at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\ \ at Sy r.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) System.ServiceModel上的System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(消息消息,Object []参数,布尔isRequest)\\ u000d \\ u000a中的版本,字符串操作,MessageDescription messageDescription,Object []参数,布尔isRequest)\\ u000d \\ u000a System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter上的System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(消息消息,Object []参数)\\ u000d \\ u000a中的.Dispatcher.OperationFormatter.DeserializeRequest(消息消息,Object []参数)\\ u000d \\ u000a Sy中的.DeserializeRequest(消息消息,对象[]参数)\\ u000d \\ u000a stem.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)\ \ at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)\ \ at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)"} 在System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin的System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc&rpc)\\ u000d \\ u000a中的stem.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(消息消息,Object []参数)\\ u000d \\ u000a (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系统中的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&rpc)\\ u000d \\ u000a位于系统的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&rpc)\\ u000d \\ u000a .ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&rpc)\\ u000d \\ u000a .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 aa class with the following attributes: 它放在一个具有以下属性的类中:

[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服务。

Use double quotes instead of single quotes in the JSON you are sending to the service. 在要发送给服务的JSON中使用双引号而不是单引号。 That is, change: 也就是说,改变:

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. 顺便说一句,我使用我在使用内置ASP.NET工具以外的库调用ASMX和WCF服务时经常使用的方法来调试它。 I called the service using the client proxy created by an asp:ScriptReference and then inspected the request being sent to the server using an HTTP sniffer (such as HttpFox for FireFox) and compared the request to the one being sent by jQuery . 我使用asp:ScriptReference创建的客户端代理调用服务,然后使用HTTP嗅探器(例如HttpFox for FireFox)检查发送到服务器的请求,并将请求与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. 在这种情况下,很明显发送的POST数据存在差异。

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.. 这是Webservice合同..

    [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) {    
  }
});

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){ function formatJsonDataToWCFPost(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;

} }

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 Service for more info. 有关详细信息,请参阅对WCF REST服务的jQuery AJAX调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM