This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center。
已关闭8年。
我正在通过以下方法使用WCF Rest服务
然后从Javascript调用此服务,如下所示:
其中object是格式的分层json
在我尝试使用的示例上方,但在服务端,所有对象字段(ID,名称,数据)为空。我没有问题。
选项2
更改对对象进行字符串化的代码,使其创建此JSON:
因为您只是发送一个参数,所以我个人会选择选项2,因为它为您节省了一些空间。我认为,如果要发送多个参数,则只需要“包装”样式即可。
已关闭8年。
我正在通过以下方法使用WCF Rest服务
[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
});
其中object是格式的分层json
在我尝试使用的示例上方,但在服务端,所有对象字段(ID,名称,数据)为空。我没有问题。
最佳答案
这是将属性设置为null,因为实际上是向它发送一个“包装”对象-您发送给它的JSON具有一个对象,该对象带有一个属性(sampleObject),这是另一个对象,即SampleObject。
因此,您有两种解决方法。
选项1
您可以将请求格式设置为包装在服务上,因此只需将操作契约(Contract)上的属性更改为以下内容:
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/SampleMethod")]
选项2
更改对对象进行字符串化的代码,使其创建此JSON:
{"ID":1, "Name":"ABC", "Data":"Sample data"}
因为您只是发送一个参数,所以我个人会选择选项2,因为它为您节省了一些空间。我认为,如果要发送多个参数,则只需要“包装”样式即可。