WCF服务:返回自定义对象

Ble*_*ony 8 wcf

我在我的应用程序中使用WCF服务.我需要在服务类中返回一个自定义对象.方法如下:

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

Service.cs
public object GetObject() 
{
  object NewObject = "Test";
  return NewObject;
}
Run Code Online (Sandbox Code Playgroud)

每当我调用该服务时,它都会抛出异常,并显示以下消息:

System.ServiceModel.CommunicationException: "An error occured while receiving the HTTP response to <service path>"
Run Code Online (Sandbox Code Playgroud)

内在例外:

System.Net.WebException: "The underlying connection was closed. An unexpected error occured on receive"
Run Code Online (Sandbox Code Playgroud)

我们不能从WCF服务返回对象类型或自定义对象吗?

Kla*_*sen 14

您应该返回标有该DataContract属性的类的实例:

[DataContract]
public class MyClass
{
    [DataMember]
    public string MyString {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

现在更改您的服务界面,如下所示:

[OperationContract]    
MyClass GetMyClass();  
Run Code Online (Sandbox Code Playgroud)

而你的服务:

public MyClass GetMyClass()      
{     
    return new MyClass{MyString = "Test"};     
} 
Run Code Online (Sandbox Code Playgroud)