How to inherit from a class that is not tagged DataContractAttribute or SerializableAttribute in WCF?

In WCF, how to inherit from a class that is not tagged DataContractAttribute or SerializableAttribute, and use this as a datacontract?

Example: I have a custom class called "EmailAttachment" that I inherited from System.Net.Mail.Attachment:

[DataContract] public class EmailAttachment : Attachment { [DataMember] public string AttachmentURL { set; get; } [DataMember] public string DisplayName { set; get; } } 

But when I publish the service, it throws a runtime error, saying that:

System.Runtime.Serialization.InvalidDataContractException: Type 'EmailAttachment' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute.

What is the workaround for this?

+4
source share
1 answer

It depends on what you want your data to look like. You cannot use a wrapper, not a derived class? Sort of:

 [DataContract] public class EmailAttachment { public EmailAttachment(){} internal EmailAttachment(Attachment inner) {_attachment = inner;} [DataMember] public string AttachmentURL { set; get; } [DataMember] public string DisplayName { set; get; } private Attachment _attachment; } 

If there is any state from the internal System.Mail.Attachment that you want to open in the data contract, you must add the DataMember properties to get this.

0
source

Source: https://habr.com/ru/post/1332255/


All Articles