WCF,POST JSONized数据

我有一个复杂的类型:

[DataContract] public class CustomClass { [DataMember] public string Foo { get; set; } [DataMember] public int Bar { get; set; } } 

然后,我有一个WCF RESTful Web服务,其中包含:

 [OperationContract] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/class/save")] bool Save(CustomClass custom); 

所以在浏览器端我将我的CustomClass对象jsonized到它看起来像:

 var myClass = "{ foo: \"hello\", bar: 2 }"; $.ajax({ contentType: "application/json", data: { custom: myClass }, dataType: "json", success: callback, type: "POST", url: "MyService.svc/class/save" }); 

我使用$ .ajax提交数据w / jquery所以我可以手动将内容类型设置为“application / json”,当它提交时,postbody看起来像

 custom= 

我收到以下错误:

服务器遇到处理请求的错误。 exception消息是’检查MyAssembly.CustomClass类型的对象的start元素时出错。 遇到意想不到的字符’c’。’。 请参阅服务器日志以获取更多详 exception堆栈跟踪是:在System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.ReadObject(消息消息)的System.Runtime.Serialization.Json.DataContractJsonSerializer.IsStartObject(XmlDictionaryReader reader)中的System.Runtime.Serialization.XmlObjectSerializer.IsStartObjectHandleExceptions(XmlReaderDelegator reader)处。 System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest上的System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(消息消息,Object []参数)处的System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.DeserializeRequest(消息消息,Object []参数)处的消息System.ServiceModel.Dispatcher.DispatchOserationRuntime.Invok上的System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc&rpc)处的System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(消息消息,Object []参数)处的消息,Object []参数) System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&rpc)中的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&rpc)处的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&rpc)处的eBegin(MessageRpc&rpc)。位于System.ServiceModel.Dispatcher.MessageRpc.Process的System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&rpc)中的ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&rpc)(Boolean isOperationContextSet)

我已经尝试包装我的json’ized数据…我尝试使用$ .post发送消息(但这并没有将contenttype设置为application / json所以web服务不明白)..任何想法?

您已正确转义对象的问题,但是当您在jQuery post方法中构建复杂的Json对象时,您无法转义包装器。 所以你需要像这样逃避整个JS对象:“{\”custom \“:\”{foo:\“hello \”,bar:2} \“}”(我实际上并没有自己试试,但应该工作), 或(可能更好的解决方案)使用JSON.stringify({custom:myClass})

WCF对它接收的用于序列化的JSON对象非常敏感。

因此,您遇到的问题是序列化错误。 WCF希望在JSON中看到包含“”的属性的名称

所以我只是遇到了同样的错误

 data:'{id: 1 }', 

没用,但是

  data:'{"id": 1 }', 

做得好

我希望这可以帮助其他人

看看你的一些答案: 如何使用JSON,jQuery向ASP.NET MVC Controller发布一系列复杂对象?