自定义ASP.Net核心JSON模型绑定器

时间:2018-05-22 10:09:53

标签: asp.net-core asp.net-core-mvc custom-model-binder

我发布的JSON对象是:

{{
 "emails": [
        {
          "To": "info@gmail.com",
          "Subject": "Subject",
          "Body": "Body",
          "ID": "d3d13242-6eff-4c57-b718-ef5ad49fe301"
        },
        {
          "To": "hr@gmail.com",
          "Subject": "Subject",
          "Body": "Body",
          "ID": "101edaf0-fcb4-48fc-9e9e-0d7492b591b0"
        }
      ]
}}

默认情况下,ASP.NET模型绑定器不会绑定此JSON对象,正如您在此处看到的那样,当我向API发送post请求时,我始终为null:

[HttpPost, Route("Send")]
public async Task<IActionResult> Send(Email[] emails)
{
  var toSave = from email in emails
                         select new EmailQueueItem
                         {
                             Html = true,
                             To = email.To,
                             Subject = email.Subject,
                             Body = email.Body
                         };

   await Database.BulkInsert(toSave.ToArray());

   return Ok();
 }

电子邮件属性始终为 null 。我很感激为创建这种JSON对象的自定义模型绑定器提供帮助。

1 个答案:

答案 0 :(得分:1)

问题是您实际上是向控制器发送一个包含一个名为emails但不是数组的属性的对象

选项一: 客户端对象只需要包含数组

 [
    {
      "To": "info@gmail.com",
      "Subject": "Subject",
      "Body": "Body",
      "ID": "d3d13242-6eff-4c57-b718-ef5ad49fe301"
    },
    {
      "To": "hr@gmail.com",
      "Subject": "Subject",
      "Body": "Body",
      "ID": "101edaf0-fcb4-48fc-9e9e-0d7492b591b0"
    }
  ]

然后从请求正文中读取数组

public async Task<IActionResult> Send([FromBody]Email[] emails)

选项2: 在客户端

中定义这样的数组时
{
  "emails":...
}

您需要通过定义包含名为emails

属性的模型来匹配控制器上的对象设置
public class RequestModel
{
    public Email[] emails { get; set; }
}

然后在控制器方法中,使用模型并从正文中读取

public async Task<IActionResult> Send([FromBody]RequestModel emails)