我正在尝试在dotnet(VS 2012)中创建一个接受JSON列表的restful web服务。有这个非常有用的帖子。
Jquery Ajax Posting json to webservice
示例是现货,但我需要对DataContract进行排序。这是我的问题:
Fiddler帖子:
{ "Markers": [
{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }
]};
在VS2012调试器中,我看到了等效的内容:
{ "Markers": [
{ "position": "0", "markerPosition": "0" },
{ "position": "0", "markerPosition": "0" },
{ "position": "0", "markerPosition": "0" }
]};
以下是代码(直接来自链接示例):
public class Marker
{
decimal position { get; set; }
int markerPosition { get; set; }
}
public string CreateMarkers(List<Marker> Markers)
{
return "Received " + Markers.Count + " markers.";
}
这是合同:
[OperationContract]
[WebInvoke(UriTemplate = "Markers", Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string CreateMarkers(List<Marker> Markers);
另一篇同样精彩的帖子解释说,需要设置datacontract以查看参数值:
WCF REST POST of JSON: Parameter is empty
我最初的问题是数据合同应该是什么。我开始时:
[OperationContract]
[WebInvoke(UriTemplate = "Markers", Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string CreateMarkers(List<Marker> Markers);
之后消息结构通过,但是null内容。然后,根据建议,我试过了:
[OperationContract]
[WebInvoke(UriTemplate = "Markers", Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
string CreateMarkers(List<Marker> Markers);
之后,消息结构和内容为空。
[OperationContract]
[WebInvoke(UriTemplate = "WrappedMarkers", Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string WrappedMarkers(MarkerRequest wrappedmarkers);
[DataContract]
public class MarkerRequest
{
[DataMember]
public List<Marker> Markers
{
get { return _markers; }
set { _markers = value; }
}
private List<Marker> _markers = new List<Marker>();
}
public string WrappedMarkers(MarkerRequest wrappedmarkers)
{
return wrappedmarkers.Markers.ToString();
}
以下是已签约的操作,已更改为WrappedRequest
结构正确,但内容再次为空。
回到原点。我似乎能够看到消息的结构。如何将内容映射到结构?
答案 0 :(得分:8)
据我所知,由于您没有在数据类上设置 [DataContract] 和 [DataMember] 属性,因此您获得'0'值。添加这些attr之后,您的类应该看起来像
[DataContract]
public class Marker
{
[DataMember]
decimal position { get; set; }
[DataMember]
int markerPosition { get; set; }
}