代码之家  ›  专栏  ›  技术社区  ›  eocron

通过类的SOAP抽象不能正常工作?

  •  1
  • eocron  · 技术社区  · 7 年前

    WCF中的原始SOAP契约(为了可读性,我特意将DTO属性修改为):

    public class A : B
    {
        public int Field1 {get;set;}
    
        public int Field2 {get;set;}
    }
    
    public abstract class B 
    {
        public int Field3 {get;set;}
    }
    

    一段时间后,这份原始合同交给客户使用。大家都很高兴。但后来我决定将一个字段移到抽象级别:

    public class A : B
    {
        public int Field2 {get;set;}
    }
    
    public abstract class B 
    {        
        public int Field1 {get;set;}//heh, become abstract
    
        public int Field3 {get;set;}
    }
    

    所以,基本上,如果这个字段被添加到每个具体的类中,这是一样的,而对于A来说什么都没有改变,但是这会破坏旧的客户机。

    为什么会这样?如何在SOAP中实现REST的灵活性,在SOAP中只需添加字段/将其从具体的类移动到抽象,一切都正常工作?

    0 回复  |  直到 7 年前
        1
  •  0
  •   Ackelry Xu    7 年前

    wcf按正确的顺序序列化和反序列化数据。 顺序是抽象类的第一个属性,然后是子类。 所以原始数据联系人的顺序是Field3->1、Field1->2、Field2->3。

    然后将Field1移到抽象类中,顺序为Field1->1、Field3->2、Field2->3。

    更改后,客户端和服务器端的属性顺序不匹配。所以你应该改变抽象类的顺序。

     [DataContract]
    public abstract class Parent
    {
       // IsRequired is used to test whether has received the property
    
     // if not, it will show error. Order could change the order of the property in message 
        [DataMember(IsRequired = true,Order =1)]
        public int Field3 { get; set; }
        [DataMember(IsRequired = true,Order =2)]
        public int Field1 { get; set; }
    
    }
    

    我知道这种方法只适用于小的更改,如果您想更改很多,请考虑使用DataContractSurrogate https://docs.microsoft.com/en-us/dotnet/framework/wcf/extending/data-contract-surrogates