微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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属性不会神奇地将数据传输对象转换为服务.

原文地址:https://www.jb51.cc/html/226348.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐