Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a KnownType in WCF

Tags:

c#

wcf

i am learning wcf. so i encounter a wcf attribute called known type. here i got a piece of code which is not clear.

[DataContract]
   public class UserAccount {}

   [DataContract]
   public class Admin : UserAccount {}

   [DataContract]
   public class Guest : UserAccount {}

[DataContract]
  [ServiceKnownType(typeof(Admin))]
  [ServiceKnownType(typeof(Guest))]
  public class SecurityInfo
  {
          [DataMember]
          private UserAccount user;
  }

now the tutorial is saying that Above code will work fine, either we set SecurityInfo data member to Admin or Guest.But if KnownTypeAttribute for Admin and Guest are not provided, deserialization engine will not recognize Admin and Guest types and will cry.

what is relation ship between SecurityInfo and admin & guest class ? i really do not understand what known type attribute is doing here. i am not familiar with known type attribute and do not know what it does and when to use it.

so i like to request please make me understand the known type attribute in such a way as a result i can understand it's use and what it is....so come with one easy sample code where i can understand what is known type attribute. thanks

like image 688
Mou Avatar asked Feb 14 '23 06:02

Mou


1 Answers

(those are over simplified explanations that illustrate the concepts, not the technical implementation in WCF).

When a message is sent over the network, using WCF for instance, it is serialized. In other words (most of the time), in text. Say XML. The XML sent by the client to the server describes the data and its structure.

<data>
  <SecurityInfo>
    <user type="UserAccount">(some further XML data here)</user>
  </SecurityInfo>
</data>

When this code is recieved, the WCF API parses the XML and tries to create C# objects you will be able to manipulate in your code. Here an instance of the Securityinfoclass with a property of type UserAccount. But how does it know which class can be instanciated?

Obviously the <user> node holds the class name in its attributes. But what if the client sent a derivated instance like the Admin class? You would receive something like this:

<data>
  <SecurityInfo>
    <user type="Admin">(some further XML data here)</user>
  </SecurityInfo>
</data>

The [KnownType] attribute informs the WCF service that "it is ok" to receive this Admin type because it is a subclass of the awaited UserAccounttype.

It is especially important when the Admin subclass has more properties, like a public string AdminEmail { get;set; }. This property will be sent by the client too. WCF server, when doing its parsing job server-side, is informed this additional property is valid since the Admin type is a valid [KnownType].

like image 192
Askolein Avatar answered Feb 15 '23 18:02

Askolein