我正在使用POST和
XML作为内容发布的REST API.在我的WebInvoke方法中,似乎只是序列化了一些属性.例如,我传递FirstName,LastName,电子邮件,电话和地址,但它没有设置电子邮件和地址属性.因此,当它将数据添加到我的数据库时,这些字段是空白的.
为什么是这样?为什么要设置一些属性而不是其他属性?我已经尝试重新安排订单,这并没有影响任何事情.这也让我想到了另外一个问题:所有属性都必须在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>JohnDoe@gmail.com</Email>
<Phone>8885551234</Phone>
<Address>123 Fake St</Address>
<City>Fake City</City>
</Lead>
最佳答案 您需要在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
}