【发布时间】:2010-11-10 12:29:42
【问题描述】:
我有一个复杂的类型:
[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”,当它提交时,postbody 看起来像
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(消息 消息,对象 [] 参数) 在 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 发送消息(但没有将内容类型设置为 application/json,因此 web 服务无法理解)..任何想法?
【问题讨论】: