【问题标题】:How to pass an array to a Web API POST method that accepts both XML and JSON payloads?如何将数组传递给同时接受 XML 和 JSON 有效负载的 Web API POST 方法?
【发布时间】:2020-03-23 21:24:34
【问题描述】:

我有一个小问题,我构建了一个接受数组对象的 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 结构。

【问题讨论】:

    标签: json xml rest asp.net-web-api serialization


    【解决方案1】:

    我终于明白了。我需要按如下方式包装我的请求,现在数据正在通过,我还在 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2012-08-21
      相关资源
      最近更新 更多