2012-04-03 103 views
2

我使用WCF休息服务与POST方法如下发送JSON到WCF REST服务 - 对象的Fileds是空的

[OperationContract] 
    [WebInvoke(Method = "POST", 
    BodyStyle = WebMessageBodyStyle.Bare, 
    RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json, 
    UriTemplate = "/SampleMethod")] 
    int SampleMethod(SampleObject sampleObject); 

,并呼吁从Javascript如下这项服务,

$.ajax({ 
     type: 'POST', 
     url: 'http://localhost/SampleService/SampleService.svc/SampleMethod', 
     data: object, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     processdata: true, 
     success: successCallback, //On Successfull service call 
     error: serviceFailed// When Service call fails 
    }); 

凡对象是在格式

的strigified JSON { “sampleObject”:{ “ID”:1, “名称”: “ABC”, “数据”: “样品数据”}}

上面我尝试使用的示例,但在服务端的所有对象字段(ID,名称,数据)为空。我没有得到这个问题。

+0

当我写了这样的代码,我从来没有指定'BodyStyle',它的工作原理。你尝试过吗?否则,我不得不看'SampleObject'进一步调查。 – madd0 2012-04-03 11:25:50

+0

您是否也可以添加您的端点配置? – 2012-04-03 19:36:29

回答

2

感谢您的回复。我发现我的错误。数据类型不匹配存在问题。像int有一个空值字符串,并且日期格式也有问题。

3

这是将属性设置为空,因为您发送它是一个“包装”对象 - 您发送它的JSON具有一个具有属性(sampleObject)的对象,它是另一个对象,它是您的SampleObject。

因此,您有两个选择来解决这个问题。

选项1

您可以将请求格式设置为包装上的服务,所以只要你的经营合同上改变你的属性如下:

[WebInvoke(Method = "POST",  
      BodyStyle = WebMessageBodyStyle.WrappedRequest, 
      RequestFormat = WebMessageFormat.Json,  
      ResponseFormat = WebMessageFormat.Json,  
      UriTemplate = "/SampleMethod")] 

选项2

更改将对象字符串化的代码,以便它创建此JSON:

{"ID":1, "Name":"ABC", "Data":"Sample data"} 

由于您只是发送一个参数,我个人会使用选项2,因为它为您节省了一些线上空间。如果你想发送多个参数,我认为你只需要“包装”风格。