Introduction
KnownType Attribute
Create a WCF application and implement the service contract and data contract as follows.
- [ServiceContract]
- public interface IsaveItem
- {
- [OperationContract]
- void Save(Item value); //Contract expects passed data to be of type Item.
- }
- [DataContract]
- public class Item
- {
- [DataMember]
- public int id { get; set; }
- [DataMember]
- public String Name { get; set; }
- [DataMember]
- public double price { get; set; }
- }
- [DataContract]
-
- public class PenItem:Item
- {
- public PenItem()
- {
- Name = "Pen Item";
- }
- }
- public class SavePenItem : IsaveItem
- {
- public void Save(Item value)
- {
- Console.WriteLine("Received Data From Client{0},{1}", value.Name,value.price);
- }
- }
Let's try to run and test the service (I have created a WCF Service library from Visual Studio to test it). The expected data contract to the service is of type Item. Now let's try to pass a type of PenItem (derived class from Item) to the service. We would get an error as in the following:
The deserializing engine expects the type to be Item and not the PenItem. That is where the KnownType Attribute is relevant, letting the engine to know that the contract could also be of type PenItem. You can let the deserializing engine know about the types in one of three ways. They are as follows:
- Using the attribute with DataContract.
- [DataContract]
- [KnownType(typeof(PenItem))]
- public class Item
- {
- [DataMember]
- public int id { get; set; }
- [DataMember]
- public String Name { get; set; }
- [DataMember]
- public double price { get; set; }
- }
- ServiceKnownTypeAttribute: Defining the known type with Service Contract
- [ServiceContract]
- [ServiceKnownType(typeof (PenItem)) ]
-
- public interface IsaveItem
- {
- [OperationContract]
- void Save(Item value);
- }
- Declarative Known Types: Defining the known type at the configuration level.
- <configuration>
- <system.runtime.serialization>
- <dataContractSerializer>
- <declaredTypes>
- <add type="Knowntype.Item,Knowntype, Version=1.0.0.0, Culture=neutral,PublickeyToken=null">
- <knownType type="knowntype.PenItem,knowntype, Version=1.0.0.0, Culture=neutral,PublicKeyToken=null"/>
- </add>
- </declaredTypes>
- </dataContractSerializer>
- </system.runtime.serialization>
- </configuration>