很多时候,我看到开发人员正在使用DataContract和DataMember属性作为他们的
Asp.net Web API模型?
有什么区别和最佳做法?
解决方法
使用DataContract的主要优点是,您可以避免XmlMediaTypeFormatter和JsonMediaTypeFormatter的一些常见序列化提示的重复属性.即您可以选择加入/选择退出要序列化的模型的特定属性,也可以重命名属性,并让两个格式化程序都尊重该属性.
例如:
[DataContract]
public class Sample {
[DataMember]
public string PropOne {get;set;}
public string PropTwo {get;set;}
[DataMember(Name="NewName")]
public string PropThree {get; set;}
}
相当于:
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;}
}
