底层连接在WCF中使用Serializers关闭

时间:2013-02-06 06:10:44

标签: wcf

我有一个带服务接口的WCF服务

[ServiceContract]    
public interface IMyService
{
    [OperationContract]
    [ServiceKnownType(typeof(Person))]
    [ServiceKnownType(typeof(Employee))]
    IPerson GetPerson();
 }

我的GetPerson实现是

 public IPerson GetPerson()
 {
        IPerson obj = new Person();
        obj.FirstName = "Bhuvan";
        obj.LastName = "Ram";        
        return obj;
  }

在我的客户端,我使用

这么简单
KnownType.MyServiceClient obj = new KnownType.MyServiceClient();
Person objp = (Person)obj.GetPerson()'

但是当我尝试访问时,我收到错误

  

底层连接已关闭:连接意外关闭。

我的堆栈跟踪就像这样

  

at System.Net.HttpWebRequest.GetResponse()
  在System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
  在System.Net.HttpWebRequest.GetResponse()
  在System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)..

我的员工类是

  

>    [DataContract(Name =“Employee”)]       [KnownType(typeof运算(IEmployee))]
      公共类员工:IEmployee       {           [数据成员]           公共字符串EmployeeName           {               获得;设置;           }       }

     

>   我的人员班是      [DataContract(Name =“Person”)]       [KnownType(typeof运算(IPerson))]
      公共类人员:IPerson    {
       #region IPerson会员        [DataMember(Name =“FirstName”)]        public string FirstName {get;组; }

 [DataMember(Name = "LastName")]
 public string LastName { get; set; }
 #endregion

}

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

Concrete类Person可能存在序列化问题。

 [ServiceContract]
 public interface IMyService
 {
    [OperationContract]
    IPerson GetPerson();
 } 

 public interface IPerson
 {
   string FirstName { get; set; }
   string LastName { get; set; }
 }

   [DataContract(Name = "Person")]
   [KnownType(typeof(IPerson))]
  public class Person : IPerson
  {
     [DataMember(Name = "FirstName")]
     public string FirstName { get; set; }

     [DataMember(Name = "LastName")]
     public string LastName { get; set; }
  }

可以在方法签名上使用ServiceKnownType属性,而不是在整个类上使用KnownType属性

[OperationContract]
[ServiceKnownType(typeof(Person))]
IPerson GetPerson();

来源:Check this link for detail

参考:Using Knowntype

注意:

  • 在任何地方使用Knowntype或仅在ServiceContract上使用ServiceKnowntype。
  • 尝试将唯一的命名空间用于Person和Employee类的DataContract。