0
votes

I'm new in WCF and now stuck in something about using custom types in WCF service.

I have two classes Class1 and Class2 in TestClass project

public Class1: ArrayList{
    public string street;
}

public Class2{
    public string name;
    public string address;
}

My WCF service TestService include function DoSomething using two above classes

public string DoSomething(Class1 c1){
     return c1.street; 
}

And when try to call this function

Class1 c1 = new Class1();
Class2 c2 = new Class2();
c1.Add(c2);
ServiceClient1.Dosomething(c1);

I get the Exception

There was an error while trying to serialize parameter http://tempuri.org/:c1. The 
InnerException message was 'Type 'WebApplication1.Class2' with data contract name 
'Class2:http://schemas.datacontract.org/2004/07/WebApplication1' is not expected. Add 
any types not known statically to the list of known types - for example, by using the  
KnownTypeAttribute attribute or by adding them to the list of known types passed to  
DataContractSerializer.'.  Please see InnerException for more details.

Can anyone tell me how to add DataContract for a class defined outside the WCF service, and how to solve this problem. Thanks a lot!

1

1 Answers

1
votes

Add the lines below to your service interface declaration (add them just below the ServiceContract attribute):

[ServiceKnownType(typeof(Class1))]
[ServiceKnownType(typeof(Class2))]

alternatively, and this is the recommended approach, define your set of DTO objects exported by the service and decorate them with [DataContract] and [DataMember] attributes.