Web Services Soap Web服务:根据条件向对象添加属性

li9yvcax  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(131)

我有一个返回对象的Soap WS

[DataContract(Namespace = Configuration.Namespace)]
  public class GetAccountResponse
  {  [DataMember]
    public List<Account> accounts { get; set; }
   }
  [DataContract(Namespace = Configuration.Namespace)]
   public class Account
  { [DataMember(Name = "GUIDAccount")]
      public Guid? accountid { get; set; }
    [DataMember]
      public List<Contract> Contracts { get; set; }
   }
     [DataContract(Namespace = Configuration.Namespace)]
       public struct Contract
        {
        [DataMember(Name = "IDContrat")]
         public string contrat { get; set; }

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

我需要向协定添加一个新属性,但仅限于特定的请求条件。

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

回应:

//all the time
    return new GetAccountResponse
                    {
                        accounts = myaccounts.Values.ToList()
                    };
                    
   //my request matches a critertia the obejcts with the new 
      attribute

       if(//mycriteria)

       return new GetAccountResponse //object with state attribute
                    {
                        accounts = myaccounts.Values.ToList()
                    };

如何通过使用相同的GetAccountResponse对象来实现这一点?

5hcedyr0

5hcedyr01#

也许您可以尝试将DataMemberAttribute的EmitDefaultValue属性设置为false。https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/data-member-default-values?redirectedfrom=MSDN
例如:

[DataContract]
class MyDC 
{
    [DataMember]
    public string DM1;

    [DataMember(EmitDefaultValue = false)]
    public string DM2;

    [DataMember]
    public string DM3;
}

然后将此属性设置为null:

[OperationContact]
public MyDC GetMyDC()
{
    MyDC mdc = new MyDC();

    if (condition)
    {
        // Code to prevent DM2 from being deserialized  
        mdc.DM2 = null;
    }

    return mdc;
}

这样,该属性就不会在序列化时写入输出流。
来源:Can I prevent a specific datamember from being deserialized?

相关问题