我有一个小问题,我构建了一个接受数组对象的WebAPI服务端点。我不确定我的DTO类是否被正确构造,或者我可能遗漏了什么,但是当我作为XML发布时,对象是空的。我已经集成了Swagger,并使用示例结构来发布数据。请参见以下代码:
型号:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public Note[] Notes { get; set; }
}
public class Note
{
public string Content { get; set; }
public DateTime CreatedDate { get; set; } = DateTime.Now;
}
控制器:
[HttpPost]
public IHttpActionResult AddStudentRecord(Student[] student)
{
return Json(student);
}
请求对象:
<?xml version="1.0"?>
<Students>
<Student>
<Name>John Doe</Name>
<Age>13</Age>
<Notes>
<Note>
<Content>Some Notes</Content>
<CreatedDate>1970-01-01T00:00:00.001Z</CreatedDate>
</Note>
</Notes>
</Student>
</Students>
什么是正确的方式来配置我的对象,使其既适合JSON又适合XML,而不会出现这个问题。如果我将列表包装在另一个名为Notes的类中,问题就出在这里,现在它搞乱了JSON结构。
发布于 2020-03-23 21:24:34
我终于想通了。我需要将我的请求包装如下,现在数据正在通过,我还在webApiConfig中包含了以下内容。
<?xml version="1.0" encoding="UTF-8"?>
<ArrayOfStudent>
<Student>
<Name>string</Name>
<Age>1</Age>
<Notes>
<Note>
<Content>string</Content>
<CreatedDate>1970-01-01T00:00:00.001Z</CreatedDate>
</Note>
</Notes>
</Student>
</ArrayOfStudent>
WebAPIConfig:
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
https://stackoverflow.com/questions/60799373
复制相似问题