我可以说以下内容绝对有效。我刚刚测试了它。对不起,它在 vb.net 中,但你应该明白。
在服务器端:在 IService1.vb
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web
Namespace Webservices
<ServiceContract()>
Public Interface IService1
<OperationContract()> _
<WebInvoke(method:="POST", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.WrappedRequest)> _
Function test(manageBusiness As ManagedBusiness) As string
End Interface
End Namespace
在 Service1.svc.vb
Imports System.Runtime.Serialization
Imports System.ServiceModel.Activation
Namespace Webservices
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Required)>
Public Class Service1
Implements IService1
Public function test(manageBusiness As ManagedBusiness) As string Implements IService1.test
Return "done"
End function
End Class
<CollectionDataContract()>
Public Class Services
Inherits List(Of Service)
End Class
<DataContract()>
Public Class Service
<DataMember()>Public Property Name As String
<DataMember()>Public Property Desc As String
<DataMember()>Public Property LongTime As Integer
End Class
<DataContract()>
Public Class ManagedBusiness
<DataMember()>Public Property Name As String
<DataMember()>Public Property Desc As String
<DataMember()>Public Property Services As Services
End Class
End NameSpace
我连接了 webconfig 设置。并将这个 jquery ajax 调用放在客户端:
$("#btnTest").click(function () {
var services = [];
services.push({
Name: "aaaaaa",
Desc: "aaaaaa",
LongTime: 30
});
services.push({
Name: "aaaaaa1",
Desc: "aaaaaa",
LongTime: 30
});
var data = {};
data.manageBusiness = {
Name: "aaaaaa",
Desc: "aaaaaaaaaaaa",
Services: services
}
$.ajax({
type: "POST",
url: "http://localhost:64110/Webservices/Service1.svc/test",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify(data),
success(msg) {
}
});
});
我可以确认请求的有效负载如下:
{"manageBusiness":{"Name":"aaaaaa","Desc":"aaaaaaaaaaaa","Services":[{"Name":"aaaaaa","Desc":"aaaaaa","LongTime":30},{"Name":"aaaaaa1","Desc":"aaaaaa","LongTime":30}]}}
WCF 服务反序列化一切都很好。我认为您缺少的是 [CollectionDataContract]属性。
更新:我尝试删除 [CollectionDataContract] 属性,它仍然有效。所以我猜测数据契约属性仅用于序列化,不需要反序列化(?)