2012-01-19 48 views
4

我正在使用POST和XML作爲內容發佈到REST API。在我的WebInvoke方法中,它似乎只是序列化一些屬性。例如,我通過名字,姓氏,電子郵件,電話和地址,但它沒有設置電子郵件和地址屬性。所以當它將數據添加到我的數據庫時,這些字段是空白的。REST API只設置對象的某些屬性

這是爲什麼?爲什麼要設置一些屬性而不是其他設置?我已經嘗試重新安排訂單並且不影響任何內容。這也讓我想到另外一個問題:所有的屬性都必須在xml中傳遞,還是隻傳遞一些像我這裏的足夠的屬性?我希望答案是不需要全部,因爲這可能是一個非常動態的系統,新的屬性可能會經常添加,而不會更改xml。

下面是一些相關的代碼:

public class Lead 
{ 
    #region Public Properties 
    [DataMember(Name = "LeadId")] 
    public int LeadId { get; set; } 
    [DataMember(Name="FirstName")] 
    public string FirstName { get; set; } 
    [DataMember(Name = "MiddleName")] 
    public string MiddleName { get; set; } 
    [DataMember(Name = "LastName")] 
    public string LastName { get; set; } 
    [DataMember(Name = "Email")] 
    public string Email { get; set; } 
    [DataMember(Name = "Email2")] 
    public string Email2 { get; set; } 
    [DataMember(Name = "Phone")] 
    public string Phone { get; set; } 
    [DataMember(Name = "Phone2")] 
    public string Phone2 { get; set; } 
    [DataMember(Name = "Address")] 
    public string Address { get; set; } 
    [DataMember(Name = "Address2")] 
    public string Address2 { get; set; } 
    [DataMember(Name = "Address3")] 
    public string Address3 { get; set; } 
    [DataMember(Name = "City")] 
    public string City { get; set; } 
    [DataMember(Name = "State")] 
    public string State { get; set; } 
    [DataMember(Name = "Zip")] etc... 

這裏的OperationContract的

[OperationContract] 
    [WebInvoke(Method = "POST", 
     UriTemplate = "leads", 
     BodyStyle= WebMessageBodyStyle.Bare, 
     RequestFormat = WebMessageFormat.Xml, 
     ResponseFormat = WebMessageFormat.Xml)] 
    string AddLead(Lead lead); 

這裏的AddLead功能的服務:

public string AddLead(Lead lead) 
    { 
     string result = lead.Submit(); 
     if (result == "Success") 
     { 
      return "Success. " + lead.LeadId; 
     } 
     else 
     { 
      return result; 
     } 
    } 

這裏是XML是我通過:

<?xml version="1.0" encoding="utf-8"?> 
    <Lead xmlns="http://www.myrenamednamespace.com/leads"> 
     <FirstName>John</FirstName> 
     <LastName>Doe</LastName> 
     <Email>[email protected]</Email> 
     <Phone>8885551234</Phone> 
     <Address>123 Fake St</Address> 
     <City>Fake City</City> 
    </Lead> 

回答

2

您需要指定DataMember上的順序。 DataContractSerializer會採用字母順序排列,除非您另行說明,否則它會忽略它在預期順序中找到的項目(這就是爲什麼它會發送電話但不發送郵件的原因)

public class Lead 
{ 
    [DataMember(Name = "LeadId", Order=1)] 
    public int LeadId { get; set; } 

    [DataMember(Name = "FirstName", Order = 2)] 
    public string FirstName { get; set; } 

    [DataMember(Name = "MiddleName", Order = 3)] 
    public string MiddleName { get; set; } 

    // ... etc 
}