WCF dictionary deserialization, where Enum type is the key

I would like to help you. I have a problem with deserializing a WCF dictionary where the Enum type is used as a key.

I have two data objects:

[DataContract] public enum MyEnum : int { [EnumMember] Value1 = 0, [EnumMember] Value2 = 1 } 

and

 [DataContract] [KnownType(typeof(MyEnum))] public class ReturnData { [DataMember] public IDictionary<Enum, string> codes; } 

In fact, the ReturnData class contains more data members, but they are not important for my example.

These data objects are returned by the method:

 [OperationContract] public ReturnData Method1() { ReturnData data = new ReturnData(); data.codes = new Dictionary<Enum, string>(); data.codes.Add(MyEnum.Value1, "stringA"); return data; } 

When I call Method1 from the client side, the following exception is thrown:

Formatting was ruled out when trying to deserialize the message: an error occurred while trying to deserialize the http://tempuri.org/:Method1Result parameter. The InnerException message was "Error on line 1 of position 522. The element http://schemas.microsoft.com/2003/10/Serialization/Arrays:Key 'contains the data' http://schemas.datacontract.org/2004/07/AMService : MyEnum '. Deserializer does not know any type that matches this contract. Add the type corresponding to "MyEnum" to the list of known types - for example, using the KnownTypeAttribute attribute or adding it to the list of known types passed to DataContractSerializer.'

Any idea how to define a ReturnData class to solve this problem?

Note. When I change ReturnData member codes to use ReturnData as the key data MyEnum instead of Enum public IDictionary<MyEnum, string> codes; , then deserialization works correctly and the data is transferred from the server to the client side without problems.

Thanks for your help.

+4
source share
2 answers

At the top of your class, add the KnownType attribute.

 using System.Runtime.Serialization; [KnownType(typeof(MyEnum))] [DataContract] public class Foo { } 
+2
source

should this line

 data.codes = new Dictionary<Enum, string>(); 

will be

 data.codes = new Dictionary<MyEnum, string>(); 
0
source

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


All Articles