WCF Disable Deserialization Order Sensitivity

后端 未结 4 575
说谎
说谎 2020-12-09 15:01

I have a recurring problem when passing Serialized objects between non-.NET Clients, and .NET WCF Services.

When WCF Deserializes objects, it is strictly dependant

4条回答
  •  独厮守ぢ
    2020-12-09 16:02

    You can use the IsRequired property of the DataMember attribute to specify that the elements are required. In that way, instead of getting "mysterious" null value, you'll get a more explicit error message indicating that a required element is missing.

    [DataContract]
    public class Foo 
    { 
      [DataMember(IsRequired=true, Order=1)]
      public int ID { get; set; } 
    
      [DataMember(IsRequired=true, Order=2)]
      public int Bar { get; set; } 
    }
    

    What's happening in your case is:

    • The DataContract expects Bar and ID elements in that order (alphabetic because you haven't specified an explicit order).

    • It encounters an ID element without a preceding Bar element. Since Bar is not required, it simply ignores it.

    • The ID element following Bar is ignored because it is in the wrong position.

    Having said that, setting IsRequired to true will only help in version 1 of your contract. Elements added in subsequent versions will normally have IsRequired set to false. MSDN has an article on data contract versioning.

提交回复
热议问题