很多次我看到开发人员在他们的 Asp.net Web API 模型中使用 DataContract 和 DataMember 属性?
有什么区别和最佳实践?
最佳答案
使用DataContract
的主要优势, 是您可以避免 XmlMediaTypeFormatter
的一些常见序列化提示的重复属性。和 JsonMediaTypeFormatter
. IE。您可以选择加入/选择退出要序列化的模型的特定属性或重命名属性,并使两个格式化程序都尊重这一点。
例如:
[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;}
}
关于asp.net - 在使用 Asp.net Web API 时使用 DataContract 和 DataMember 属性有什么好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14089455/