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>
<Allergies>
<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: