Wednesday, May 3, 2017

knowntype attribute in WCF

KnownTypeAttribute class allows you to specify the types that should be included for consideration during deserialization.
The WCF service generally accepts and returns the base type. If you want to use inherired type at this point
than you have to use knowntype attribute.

Life without knowntype
Wihtout knowntype, you can not use a subclass of contract class, with the help of
knowtype you can make subclass of contract class.

Example :

using System.Runtime.Serialization;  
using System.ServiceModel;  
  
namespace WcfDemo  
{  
    [ServiceContract]  
    public interface IEmp  
    {  
        [OperationContract]  
        Emp GetEmp();  
  
        [OperationContract]  
        Emp  GetEmpById(Emp  builder);  
    }  
      
    [KnownType(typeof(DayBasic))]  
    [KnownType(typeof(ContractBasis))]  
    [DataContract]  
    public class Emp  
    {  
        [DataMember]  
        public int EmpId { get; set; }  
  
        [DataMember]  
        public string EmpName { get; set; }  
  
        [DataMember]  
        public string MobileNo { get; set; }  
  
        public enum EmpType { DayBasic = 1, ContractBasis = 2 }  
    }  
  
    public class Permanent : Emp
    {  
        public int AnnualSalary{ get; set; }  
     
    }  
  
    public class ContractBasis : Emp  
    {  
        public int TotalAmount { get; set; }  
        public int DayComplited { get; set; }  
    }  
}  

No comments:

Followers

Link