WCF,POST JSONized数据

时间:2009-07-14 01:57:57

标签: .net jquery wcf json post

我有一个复杂的类型:

[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=<uri encoded version of myClass>

我收到以下错误:

服务器在处理请求时遇到错误。异常消息是'那里  是一个错误检查MyAssembly.CustomClass类型的对象的start元素。遇到意外  字符'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 []参数)    at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message  message,Object []参数)    在System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(消息消息) ,Object []参数)    在System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(消息消息,对象) []参数)    在System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc&amp; rpc)    在System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)    在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)    在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc)    在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc)    在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc)    在System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc)    在System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

我已经尝试包装我的json'ized数据...我已经尝试使用$ .post发送消息(但是没有将contenttype设置为application / json,因此webservice不理解)..任何想法?

3 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:3)

因此,您遇到的问题是序列化错误。 WCF希望看到包含“”

的JSON中的属性名称

所以我刚遇到同样的错误

data:'{id: 1 }',

没有用,但是

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

做了工作

我希望这可以帮助其他人

答案 2 :(得分:0)