代码之家  ›  专栏  ›  技术社区  ›  Per Hornshøj-Schierbeck

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

  •  23
  • Per Hornshøj-Schierbeck  · 技术社区  · 16 年前

    我使用以下代码调用wcf服务。如果我调用一个(test)方法,该方法不接受任何参数,但返回一个字符串,那么它可以正常工作。如果我在方法中添加一个参数,我会得到一个wierd错误:

    {“ExceptionDetail”:{“HelpLink”:null,“InnerException”:null,“Message”:“令牌“\”,但在System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader,String res,String arg1,String arg2,String arg3)\u000d\u000a在System.Xml.XmlExceptionHelper.ThrowTokenExpected(XmlDictionaryReader读取器,应为字符串,找到字符)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializePropertyFormatter.DeserializeBodyCore(System.ServiceModel.Dispatcher.DataContractJsonSerializePropertyFormatter.DeserializeBody上的XmlDictionaryReader读取器,对象[]参数,布尔值isRequest)\u000d\u000a(XmlDictionaryReader读取器,消息版本,字符串操作,消息描述MessageDescription,对象[]参数,布尔值isRequest)\u000d\u000a位于System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContent(消息消息,对象[]参数,布尔isRequest)\u000d\u000a位于System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(消息,对象[]参数)\u000d\u000a位于System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(消息消息,对象[]参数)\u000d\u000a位于System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(消息消息,对象[]参数)\在System.ServiceModel.Dispatcher.CompositeDispatchedFormatter.DeserializeRequest(消息消息,对象[]参数)\u000d\u000a在System.ServiceModel.Dispatcher.DispatcherOperationRuntime.DeserializeInputs(MessageRpc&rpc)\u000d\u000a在System.ServiceModel.Dispatcher.DispatcherOperationRuntime.InvokeBigin(MessageRpc&rpc)\在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&rpc)上的u000d\u000a在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&rpc)上的u000d\u000a在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&rpc)上的u000d\u000a\System.ServiceModel.Dispatcher.ImmutableDispatcherRuntime.ProcessMessage2(MessageRpc&rpc)上的u000d\u000a在System.ServiceModel.Dispatcher.ImmutableDispatcherRuntime.ProcessMessage1(MessageRpc&rpc)上的u000d\u000a在System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)上的“类型”:“System.Xml.XmlException”}ExceptionType“:”System.Xml.XmlException“,”Message“:”标记“\”,但在System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader,String res,String arg1,String arg2,String arg3)”处找到“,”StackTrace“:”在System.Xml.XmlExceptionHelper.ThrowTokenExpected处的u000d\u000a(XmlDictionaryReader读取器,应为字符串,找到字符)\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.ParseStartElement()\u000d\u000a at System.Runtime.Serialization.Json.XmlJsonReader.Read()\u000d\u000a at System.ServiceModel.Dispatcher.DataContractJsonSerializePropertyFormatter.DeserializeBodyCore(System.ServiceModel.Dispatcher.DataContractJsonSerializePropertyFormatter.DeserializeBody上的XmlDictionaryReader读取器,对象[]参数,布尔值isRequest)\u000d\u000a(XmlDictionaryReader读取器,消息版本,字符串操作,消息描述MessageDescription,对象[]参数,布尔值isRequest)\u000d\u000a位于System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContent(消息消息,对象[]参数,布尔isRequest)\u000d\u000a位于System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(消息,对象[]参数)\u000d\u000a位于System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(消息消息,对象[]参数)\u000d\u000a位于System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(消息消息,对象[]参数)\在System.ServiceModel.Dispatcher.CompositeDispatchedFormatter.DeserializeRequest(消息消息,对象[]参数)\u000d\u000a在System.ServiceModel.Dispatcher.DispatcherOperationRuntime.DeserializeInputs(MessageRpc&rpc)\u000d\u000a在System.ServiceModel.Dispatcher.DispatcherOperationRuntime.InvokeBigin(MessageRpc&rpc)\在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&rpc)上的u000d\u000a在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&rpc)上的u000d\u000a在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&rpc)上的u000d\u000a\u000d\u000a位于System.ServiceModel.Dispatcher.ImmutableDispatcheRuntime.ProcessMessage2(MessageRpc&rpc)\u000d\u000a位于System.ServiceModel.Dispatcher.ImmutableDispatcheRuntime.ProcessMessage1(MessageRpc&rpc)\u000d\u000a位于System.ServiceModel.Dispatcher.MessageRpc.Process(布尔等操作上下文集)}

    $.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;
        }
    });
    

    wcf服务如下所示:

        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), OperationContract]
        public string Get7DaysStatistics(string customerId)
        {
            Debug.WriteLine(customerId);
            return "Test done";
        }
    

    它被放置在具有以下属性的类中:

    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    

    我不会在web.config中列出配置来保持这条长消息的“简短”,但如果有人认为他们可以使用它,我可以发布它——我只是想强调,只要我不向wcf服务传递任何数据,我可以调用一个方法并获得一个结果字符串,甚至可以读取一个json对象。

    4 回复  |  直到 16 年前
        1
  •  33
  •   Daniel Richardson    16 年前

    在发送到服务的JSON中使用双引号而不是单引号。即改变:

    data: "{'customerId': '2'}",
    

    data: '{"customerId": "2"}',
    

    我已经在本地进行了测试,这解决了问题。

    asp:ScriptReference HttpFox 对于FireFox),并将请求与 jQuery . 然后,您通常可以快速看到请求的不同之处(因此可能是错误的)。在这种情况下,发送的POST数据显然存在差异。

        2
  •  2
  •   Yossi Dahan    13 年前

    我只认为发布对于用户名和密码登录功能是必不可少的,所以这就是我对发送到web服务的JSon参数进行编码的方式。。。

        [ServiceContract]
        public interface ILogonService
        {
        [OperationContract]
        [WebInvoke(
          Method = "POST",
          BodyStyle = WebMessageBodyStyle.WrappedRequest,
          ResponseFormat = WebMessageFormat.Json
        )]
        string Logon(string un, string pw);
        }
    

    以下是JQuery(注意“and”的用法很重要!)

    $.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) {    
      }
    });
    
        3
  •  1
  •   Paulo Silva    14 年前

    函数格式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;
    

    }

        4
  •  0
  •   davogones    16 年前

    我认为在您的操作中,您需要以下属性:

    [WebInvoke(Method="POST",
               BodyStyle=WebMessageBodyStyle.Wrapped,
               ResponseFormat=WebMessageFormat.Json
    )]
    

    看见 jQuery AJAX calls to a WCF REST Service 更多信息。

    推荐文章