WCF将对象返回给客户端

我正在尝试使用WCF,我想我已经遇到了障碍.我的问题是我可以从“客户端”调用Add(double,double)和getPerson().但是,我无法调用Person对象的任何方法.我用裸方法剥离了类.这是我的代码片段,请让我知道我做错了什么..

服务器代码

namespace Test.WebSvc{
  [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Sample")]
  public interface ICalculator
  {
    [OperationContract]
    double Add(double n1,double n2);
    [OperationContract]
    Person getPerson();
  }


 public class CalculatorService : ICalculator
 {
    public double Add(double n1,double n2) { return n1+n2 ; }
    public Person getPerson(){ 
    Person tempPerson = new Person();
    return tempPerson; 
    }
 }

 [DataContract]
 public class Person{
 [OperationContractAttribute]
 public string toString(){
 return "This is a Person Object";
 }

客户代码

ServiceRef1.CalculatorClient client = ServiceRef1.CalculatorClient();//works
Console.WriteLine(client.Add(1.0,2.0)); //this too works   
ServiceRef1.Person p = client.getPerson(); // this is OK.,but is not doing what I wanted it to do
Console.WriteLine(p.toString()); // I do not get "This is Person Object"

我猜测我的Person类声明出了什么问题..但是dint得到一个线索我应该做什么或者我错过了什么..

谢谢!

解决方法

你正在将两个概念与你的Person类型混合在一起 – 你所做的事情是行不通的.

您已在Person类型上放置DataContract属性.这是正确的,因为您有一个返回Person的服务. Person对象将被序列化并返回给您的服务客户端(在本例中为CalculatorClient).

您应该像这样定义Person:

[DataContract]
public class Person
{
    [DataMember]
    public string Description { get; set; }
}

在您的计算器服务中:

public Person getPerson()
{ 
    Person tempPerson = new Person();
    tempPerson.Description = "This is a Person Object";
    return tempPerson; 
}

这是因为您的Person对象的工作是保存数据,并将其从服务器传送到客户端.定义方法/操作不是它的工作,而应该在您的服务类(例如CalculatorService)中完成.添加OperationContract属性不会神奇地将数据传输对象转换为服务.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 <div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些