Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF service: Returning custom objects

Tags:

wcf

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?

like image 768
Blessy Antony Avatar asked Dec 29 '09 13:12

Blessy Antony


2 Answers

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"};     
} 
like image 126
Klaus Byskov Pedersen Avatar answered Nov 03 '22 07:11

Klaus Byskov Pedersen


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

like image 35
John Saunders Avatar answered Nov 03 '22 07:11

John Saunders