使用Asp.net Web API时,使用DataContract和DataMember属性有什么好处吗?

很多时候,我看到开发人员正在使用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;}
}

相关文章

一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....
推荐一款比较牛的富文本编辑器:http://kindeditor.net/
一、异或运算异或,英文为exclusive OR,或缩写成xor异或(x...
一、云计算概念 云计算(cloud computing)是基于互联网的相...