WCF 服务:返回自定义对象 [英] WCF service: Returning custom objects
本文介绍了WCF 服务:返回自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的应用程序中使用 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>"
内部异常:
System.Net.WebException: "The underlying connection was closed. An unexpected error occured on receive"
我们不能从 WCF 服务返回对象类型或自定义对象吗?
Can't we return object types or custom objects from the WCF service?
推荐答案
你应该返回一个用 DataContract
属性标记的类的实例:
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();
以及您的服务:
public MyClass GetMyClass()
{
return new MyClass{MyString = "Test"};
}
这篇关于WCF 服务:返回自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文