WCF Service: Returning Custom Objects

I am using the WCF service in my application. I need to return a custom object to a service class. The method is as follows:

IService.cs: [OperationContract] object GetObject(); Service.cs public object GetObject() { object NewObject = "Test"; return NewObject; } 

Whenever I call the service, it throws an exception with the following message:

 System.ServiceModel.CommunicationException: "An error occured while receiving the HTTP response to <service path>" 

Internal exception:

 System.Net.WebException: "The underlying connection was closed. An unexpected error occured on receive" 

Can't return object types or custom objects from the WCF service?

+7
wcf
source share
3 answers

You must return an instance of the class marked with the DataContract attribute:

 [DataContract] public class MyClass { [DataMember] public string MyString {get; set;} } 

Now change your service interface like this:

 [OperationContract] MyClass GetMyClass(); 

And your service:

 public MyClass GetMyClass() { return new MyClass{MyString = "Test"}; } 
+13
source share

You must return a specific type, not an "object." An “object” can be of any type.

+1
source share

Custom objects are fine, while MS says you no longer need to use the [DataContract] or [datamember] attributes, I was not successful without them. Try tagging your custom object with attributes and see what happens. You can get more information about what is explicitly happening by enabling tracing and using svcutil to get tracing.

0
source share

All Articles