使用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;}
}

dawei

【声明】:淮南站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。