我有一个复杂的类型:

[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对象进行了json处理,如下所示:
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提交带有jquery的数据,因此可以将内容类型手动设置为“application/json”,并且提交时,后主体看起来像
custom=<uri encoded version of myClass>

我收到以下错误:

服务器在处理请求时遇到错误。异常消息是“那里
是错误检查类型为MyAssembly.CustomClass的对象的开始元素。遇到意外
字符“c”。有关更多详细信息,请参见服务器日志。异常堆栈跟踪为:
在System.Runtime.Serialization.XmlObjectSerializer.IsStartObjectHandleExceptions中
(XmlReaderDelegator阅读器)
在System.Runtime.Serialization.Json.DataContractJsonSerializer.IsStartObject(XmlDictionaryReader
读者)
在System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.ReadObject(消息)
在System.ServiceModel.Dispatcher.SingleBodyParameterMessageFormatter.DeserializeRequest(消息
,Object []参数)
在System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
消息,Object []参数)
在System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(消息
,Object []参数)
在System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(消息,对象
[] 参数)
在System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc&rpc)
在System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&rpc)处
在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&rpc)处
在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&rpc)
在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&rpc)处
在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&rpc)处
在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&rpc)处
在System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

我试过包装我的json化数据...我试过使用$ .post来发送消息(但是这不会将contenttype设置为application/json,因此Web服务无法理解)..有什么想法吗?

最佳答案

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

WCF确实对它要序列化的JSON对象敏感。

关于.net - WCF,发布JSON化数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1123093/

10-11 12:12