Search code examples
c#wcfdatacontractdatamember

WCF return Class with object field


I have a Wcf service that works as RestApi

[KnownType(typeof(myClass1))]
[KnownType(typeof(myClass2))]
[KnownType(typeof(myClassAndOther23typesOmmited))]
[DataContract]
public class ApiResult
{
    [DataMember]
    public bool Success { get; private set; }

    [DataMember]
    public object Result { get; private set; }
}

Field Result is problematic part, it cannot be serialized as it's an object type. So the question is, how to return proper ApiResult object.

Note

Althought there is KnownTypeAttribute, service throws SerializationException when i try to assign string[] to ApiResult Result field and return to client.

Upd

After trying ApiResult<T> Service compiled successfully, and intellisense gives this Intellisense Suggestion for generic types

After few investigations, gathered that those weird type names are made to avoid collisions in service (it's simple hashcode of type which were achieved by GetHash() of literally object),

This is responce to nvoigt solution as couldnt insert image to comment


Solution

  • Why don't you create a generic ApiResult:

    [DataContract]
    public class ApiResult<T>
    {
        [DataMember]
        public bool Success { get; internal set; }
    
        [DataMember]
        public T Result { get; internal set; }
    }
    

    That way, your method can actually return a typed value like ApiResult<myClass1> and you don't need any KnownTypes at all.