WCF custom object returns correctly apart from returning empty Lists
I send XML to my webservice and the receiving method is:
public XElement SubmitRecipe(Recipe recipe)
The recipe parameter is correctly receiving all properties but recipe.Allergies has a count of 0, does anyone know why?
Sample XML file:
<Recipe>
<Allergies>
<Allergy>nuts</Allergy>
<Allergy>wheat</Allergy>
</Allergies>
<Title>recipe title</Title>
<Id>107</Id>
</Recipe
The Recipe object:
[CollectionDataContract(Name = "Allergies", ItemName = "Allergy")]
public class AllergyList : List<string> { }
[DataContract]
public class Recipe
{
[DataMember(Name = "Allergies")]
public AllergyList Allergies { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string Title { get; set; }
}
In my create method test I get what I expect:
public Recipe GetRecipe()
{
Recipe recipe = new Recipe();
recipe.Id = 1;
recipe.Allergies = new AllergyList();
recipe.Allergies.Add("nuts");
recipe.Allergies.Add("wheat");
}
<Recipe>
<A开发者_高级运维llergies>
<a:Allergy>nuts</a:Allergy>
<a:Allergy>wheat</a:Allergy>
</Allergies>
<Id>1</Id>
</Recipe>
You may be having an XML Namespace (not .NET namespace) problem with your service contracts. The test example you show has the "a:Allery" element to refer to the collection items. While the sample XML doesn't contain the "a:" XML namespace alias. I almost always set the Namespace for all the service, operation and data contracts. Yes, it can tedious to do this but the payoff is that you will not have any XML namespace problems and it will definitely help with data contract versioning down the road. Here is what your contract would look like:
[CollectionDataContract(Name = "Allergies", ItemName = "Allergy",
Namespace="http://yourorg.co.uk/2011/05/Medical")]
public class AllergyList : List<string> { }
[DataContract(Namespace="http://yourorg.co.uk/2011/05/Medical")]
public class Recipe
{
[DataMember(Name = "Allergies")]
public AllergyList Allergies { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string Title { get; set; }
}
Check what is going across the wire with Fiddler (or something similar) and compare by creating instances of your types and serializing them to file (for example) with the DataContractSerializer (example here). The file output will show what the serializer is expecting, and you can see any differences with what your client is sending with what was logged in Fiddler - e.g. namespace differences
Another option is to use a different client where you can manually set the XML (soapUI for example).
精彩评论