WebAPI-用json发布到字典

本文关键字:字典 json WebAPI- | 更新日期: 2023-09-27 18:25:19

我有一个web api方法,看起来像这样:

[HttpPost]
[Route("messages")]
public IHttpActionResult Post(IEnumerable<Email> email)
{
    AddToQueue(email);
    return Ok("message added to queue");
}

我的电子邮件类当前如下:

public string Body { get; set; }
public string From { get; set; }
public string Template { get; set; }
public string To { get; set; }        
public string Type { get; set; }

我用fiddler在我的Post方法上发帖,就像这样:

User-Agent: Fiddler
Host: localhost:3994
Content-Length: 215
Content-Type: application/json; charset=utf-8
[
{"Body":"body","From":"from","To":"to","Template":"template"},
{"Body":"body1","From":"from1","To":"to1","Template":"template1"},
{"Body":"body2","From":"from2","To":"to2","Template":"template2"}
]

这很好用。然而,我希望能够在我的电子邮件类中添加一个字典,所以它看起来像这样:

public string Body { get; set; }
public string From { get; set; }
public string Template { get; set; }
public string To { get; set; }        
public string Type { get; set; }
public Dictionary<string, string> HandleBars { get; set; }

我把我的请求改成这样:

[{
   "Body": "body",
   "From": "from",
   "To": "to",
   "Template": "template",
   "HandleBars": [{
      "something": "value"
    }]
}, 
{
   "Body": "body1",
   "From": "from1",
   "To": "to1",
   "Template": "template1"
 }, 
 {
   "Body": "body2",
   "From": "from2",
   "To": "to2",
   "Template": "template2"
 }]

但是,当Post方法收到此消息时,除了HandleBars字典外,所有的电子邮件字段都会被填充。我必须做些什么才能正确地传递它?我的json结构不正确吗?

WebAPI-用json发布到字典

默认的JsonFormatter无法从Javascript Array绑定Dictionary,因为它没有为每个项定义一个键。

您需要使用Object

"HandleBars": {
  "something": "value"
}

您应该有

{
   "Body": "body",
   "From": "from",
   "To": "to",
   "Template": "template",
   "HandleBars": [
        { key: 'key1', value: 'something'}
    ]
}