开发者

How to return a IList in json format in a WCF RESTful service?

开发者 https://www.devze.com 2023-02-09 14:54 出处:网络
Is it possible to have a method signature like this in a WCF 3.5 service (Offer is a custom class with DataContractAttribute and DataMemberAttribute):

Is it possible to have a method signature like this in a WCF 3.5 service (Offer is a custom class with DataContractAttribute and DataMemberAttribute):

[OperationContract]
[WebGet(UriTemplate = "GetOffers", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
IList<Offer> GetOffers();

Because if I type in a web browser the corr开发者_如何转开发esponding URL, I get a serialization error (I think it's because IList doesn't have Serializable attribute so the json serializer is unable to serialize it).

The workaround would be to use a method signature like this one:

[OperationContract]
[WebGet(UriTemplate = "GetOffers", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
List<Offer> GetOffers();

Resulting in the same serialized output (a simple json array), but as the first one works with XML, I was wondering if there was a way to make it work in json, keeping the same signature.

Edit: Ok it does not work with XML serialization either, so the behavior seems to be normal. Question still stands, is it possible to keep this signature and change the serializer behavior to make this work? How?


I believe you need to add the hard collection types you use to the list of known types. See http://msdn.microsoft.com/en-us/library/ms730167.aspx for a conceptual explanation, see http://msdn.microsoft.com/en-us/library/ms751512.aspx for a sample, and see http://msdn.microsoft.com/en-us/magazine/gg598929.aspx for a very well-written MSDN Magazine article.

Also, please see the top two answers here: How do you configure WCF known types programmatically?

0

精彩评论

暂无评论...
验证码 换一张
取 消