WebAPI - 用json发布到字典

时间:2015-12-01 20:59:52

标签: c# dictionary asp.net-web-api

我有一个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"}
]

这很好用。但是,我希望能够将Dictionary添加到我的Email类中,所以它看起来像这样:

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结构不正确吗?

2 个答案:

答案 0 :(得分:10)

默认JsonFormatter无法绑定来自Javascript Dictionary的{​​{1}},因为它没有为每个项目定义键。

您需要使用Array代替:

Object

答案 1 :(得分:0)

你应该

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