Blessy Antony
Blessy Antony

Reputation: 113

WCF service: Returning custom objects

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

IService.cs:
[OperationContract]
object GetObject();

Service.cs
public object GetObject() 
{
  object NewObject = "Test";
  return NewObject;
}

Whenever i make a call to the service, it throws an exception with the following message:

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

Inner Exception:

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

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

Upvotes: 9

Views: 17806

Answers (3)

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

You should return an instance of a class that is marked with the DataContract attribute:

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

Now change your service interface like so:

[OperationContract]    
MyClass GetMyClass();  

And your service:

public MyClass GetMyClass()      
{     
    return new MyClass{MyString = "Test"};     
} 

Upvotes: 15

Steve
Steve

Reputation: 12004

Custom objects are fine, while MS says you don't have to use the [DataContract] or [datamember] attributes anymore, I haven't been successful without them. Try marking you custom object with the attributes and seeing what is going on. You can get more information as to what is explicitly happening by turning on tracing and using svcutil to get trace.

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

You should return a specific type, not "object". An "object" could be of any type.

Upvotes: 1

Related Questions