Problem with DataContract and hierarchy in WCF

I have a problem with an object in my wcf project. I can say this object:

[DataContract(Name="ClassA")] public class Person{ //---attributes--- } [DataContract(Name="ClassB")] public class Men : Person{ //---attributes--- } 

Where ClassB is a child of ClassA on the other hand. Then I have a post method:

 [OperationContract] [WebInvoke(UriTemplate= "Person", ResponseFormat = WebMessageFormat.Json, Method= "POST")] public string PostPerson(Person person) { if(person is Men){ //code... } } 

The fact is that I receive a person (on the other hand, they send as ClassB), but the person Male returns false .. why?

+4
source share
2 answers

You need to add the [ServiceKnownType(typeof(Men))] attribute to the PostPerson method.

+1
source

As Ryan Gross mentions, you need people to be a famous type. Here's a similar question / answer here about SO. One option not mentioned in the related article is the KnownType attribute . Here is an example of the code I used in the past. The premise is that this class is the base class for all your data contracts, and all your data contracts are in the same assembly:

 /// <summary> /// Base class for all data contracts. /// </summary> [DataContract(Name = "Base", Namespace = "your namespace")] [KnownType("GetKnownTypes")] public class BaseDC : IExtensibleDataObject { #region Constants and Fields /// <summary> /// Instance used to control access to the known types list. /// </summary> private static readonly object _knownTypesLock = new object(); /// <summary> /// Classes derived from this class. Needed to ensure proper functioning of the WCF data /// constract serializer. /// </summary> private static List<Type> _knownTypes; #endregion #region Properties /// <summary> /// Gets or sets an <c>ExtensionDataObject</c> that contains data that is not recognized as belonging to the /// data contract. /// </summary> public ExtensionDataObject ExtensionData { get; set; } #endregion #region Public Methods /// <summary> /// Enumerates the types in the assembly containing <c>BaseDC</c> that derive from <c>BaseDC</c>. /// </summary> /// <returns>List of <c>BaseDC</c>-derived types.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Not appropriate for a property.")] public static IEnumerable<Type> GetKnownTypes() { lock (_knownTypesLock) { if (_knownTypes == null) { _knownTypes = new List<Type>(); Assembly contractsAssembly = Assembly.GetAssembly(typeof(BaseDC)); Type[] assemblyTypes = contractsAssembly.GetTypes(); foreach (Type assemblyType in assemblyTypes) { if (assemblyType.IsClass && !assemblyType.IsGenericType) { if (assemblyType.IsSubclassOf(typeof(BaseDC))) { _knownTypes.Add(assemblyType); } } } _knownTypes.Add(typeof(BaseDC)); } return _knownTypes; } } #endregion } 
0
source

All Articles