我在WEB API
项目中遇到了这个奇怪的问题。
这是我项目的代码片段:
模特课程:
[DataContract]
public class StudentInfo
{
[Key]
[DataMember]
[StringLength(20)]
public string StudentId {get; set;}
[Key]
[DataMember]
[StringLength(20)]
public string FirstName {get; set;}
[Key]
[DataMember]
[StringLength(20)]
public string LastName {get; set;}
[DataMember]
[StringLength(20)]
public string ContactNumber {get; set;}
[DataMember]
[StringLength(20)]
public string Gender {get; set;}
[DataMember]
[StringLength(20)]
public string Course {get; set;}
[DataMember]
public DateTime? CreatedDate {get; set;}
}
控制器类方法:
[Route("/Student/AddNewStudent")]
[HttpPost]
public IHttpActionResult AddNewStudent([FromBody]StudentInfo studentInfo)
{
/* Business Logic Here */
}
我正在使用fiddler将以下xml发布到控制器:
<StudentInfo xmlns:www.w3........ xmlns:something>
<StudentId>ST00001</StudentId>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
<ContactNumber>9001236597</ContactNumber>
<Gender>MALE</Gender>
<Course>Computer Science</Course>
<CreatedDate /> -- Value assigned from controller code
</StudentInfo >
该方法已成功从 Fiddler 调用,但并非所有属性都与xml元素值绑定。
studentInfo对象如下所示:
StudentId ST00001
FirstNme null
LastNme null
ContactNumber null
Gender null
Course null
CreatedDate 01/01/0001T:00:00 -- Value is being changed by the controller
code later.
我尝试删除了DatContract和DataMember attrributes,但结果是一样的。我使用默认的 DataContractSerialization ,并尝试使用 XMLSerialization ,但没有用。
请让我知道我在这里缺少什么,我该如何解决。
答案 0 :(得分:0)
根本原因是缺少Order
属性。我按照以下方式更新了您的模型,并按预期进行了解析:
[DataContract]
public class StudentInfo
{
[Key]
[DataMember(Order = 0)]
[StringLength(20)]
public string StudentId { get; set; }
[Key]
[DataMember(Order = 1)]
[StringLength(20)]
public string FirstName { get; set; }
[Key]
[DataMember(Order = 2)]
[StringLength(20)]
public string LastName { get; set; }
[DataMember(Order = 3)]
[StringLength(20)]
public string ContactNumber { get; set; }
[DataMember(Order = 4)]
[StringLength(20)]
public string Gender { get; set; }
[DataMember(Order = 5)]
[StringLength(20)]
public string Course { get; set; }
[DataMember(Order = 6)]
public DateTime? CreatedDate { get; set; }
}
同时考虑在请求中跳过CreatedDate
,因为您希望服务器填写它。正文应如下所示(不要忘记将MvcApplication3.Controllers
替换为您的命名空间:
<StudentInfo xmlns="http://schemas.datacontract.org/2004/07/MvcApplication3.Controllers">
<StudentId>ST00001</StudentId>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
<ContactNumber>9001236597</ContactNumber>
<Gender>MALE</Gender>
<Course>Computer Science</Course>
</StudentInfo >