Are there any advantages to using the DataContract and DataMember attributes when working with the Asp.net Web API?

How many times have I seen a developer use the DataContract and DataMember attributes for their Asp.net Web-API model?

What are the differences and best practices?

+6
source share
1 answer

The main benefit of using DataContract is that you can avoid duplicating attributes for some common serialization tips for XmlMediaTypeFormatter and JsonMediaTypeFormatter . That is, you can select / exclude certain model properties that will be serialized or rename the property, and both developers agree with this.

For instance:

 [DataContract] public class Sample { [DataMember] public string PropOne {get;set;} public string PropTwo {get;set;} [DataMember(Name="NewName")] public string PropThree {get; set;} } 

is equivalent to:

 public class Sample { public string PropOne {get;set;} [XmlIgnore] [JsonIgnore] public string PropTwo {get;set;} [JsonProperty(PropertyName = "NewName")] [XmlElement("NewName")] public string PropThree {get; set;} } 
+8
source

All Articles