WCF Web API 0.6 - Returning List<T> in HttpResponseMessage throws an exception

你。 提交于 2019-12-12 03:08:43

问题


I'm fairly new to the WCF Web API, I have a basic service going and trying to leverage the full power of using HttpResponseMessage as return type. I am trying to return a List and getting the following error around which I can't get around.

This is a very basic straight-up XML service.

Any ideas would be appreciated. Thanks.

Type 'System.Net.Http.HttpResponseMessage`1[System.Collections.Generic.List`1[Entities.UploadedDocumentSegmentType]]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

Here's my service:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DocumentService
{
    [WebGet(UriTemplate = "/GetAllUploadableDocumentTypes")]
    public HttpResponseMessage<List<UploadedDocumentSegmentType>> GetAllUploadableDocumentTypes()
    {
       UploadedDocumentManager udm = new UploadedDocumentManager();
       return new HttpResponseMessage<List<UploadedDocumentSegmentType>>(udm.GetAllUploadableDocumentTypes());                                        
    }
}

The class UploadedDocumentSegmentType is defined as such:

[Serializable]
public class UploadedDocumentSegmentType
{
    public UploadedDocumentSegmentType();

    public int DocTracSchemaID { get; set; }
    public int ID { get; set; }
    public string Type { get; set; }
}

And I tried this too:

[Serializable]
[DataContract]
public class UploadedDocumentSegmentType
{
    public UploadedDocumentSegmentType();

    [DataMember]
    public int DocTracSchemaID { get; set; }
    [DataMember]
    public int ID { get; set; }
    [DataMember]
    public string Type { get; set; }
}

UDPATE: I used WCF REST Service Application Visual Studio template to create the service. I tried from scratch and change the return type on the sample WebGET method to WebResponseMessage and it would throw the same error there. So it's not my code, it's some configuration thing which for the life of me I can't figure out..


回答1:


Why do you need to return a List<T>? Just return an array and it should be okay. I don't think the built-in JSON-Serializer knows how to handle a List<T>. A reasonable thing to not know how to do as a List<T> is "editable" via add/remove type calls.

Also, you don't need the datacontract/member attributes with wcf-web-api.



来源:https://stackoverflow.com/questions/9165399/wcf-web-api-0-6-returning-listt-in-httpresponsemessage-throws-an-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!