Is there any benifit in using DataContract and DataMember attributes while working with Asp.net Web API?
Asked Answered
Q

1

8

Many time i saw that developer are using DataContract and DataMember Attributes for their Asp.net Web API model?

What are the differences and best practices?

Quilmes answered 30/12, 2012 at 8:44 Comment(0)
I
15

The main advantage of using DataContract, is that you can avoid duplicate attributes for some common serialization hints for XmlMediaTypeFormatter and JsonMediaTypeFormatter. I.e. you can opt-in/opt-out specific properties of a model to be serialized or rename a property and have both formatters respect that.

For example:

[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;}
}
Indoors answered 30/12, 2012 at 11:50 Comment(1)
it's also used to validate the received model for required members when you set "IsRequired" to true.Dermatology

© 2022 - 2024 — McMap. All rights reserved.