WebAPI-使用JSON发布到字典 [英] WebAPI - Posting to dictionary with json
问题描述
我有一个如下所示的Web api方法:
I have a web api method that looks like this:
[HttpPost]
[Route("messages")]
public IHttpActionResult Post(IEnumerable<Email> email)
{
AddToQueue(email);
return Ok("message added to queue");
}
我的电子邮件课程目前看起来像这样:
My Email class looks like this currently:
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; }
我正在使用小提琴手将其发布到我的Post方法中,如下所示:
And I'm posting to my Post method using fiddler, like this:
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"}
]
这很好.但是,我希望能够向我的Email类添加一个Dictionary,所以它看起来像这样:
This works fine. However, I want to be able to add a Dictionary to my Email class, so it will look like this:
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; }
我更改了请求,使其看起来像这样:
And I changed my request to look like this:
[{
"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词典之外的所有Email字段.为了正确传递,我该怎么办?我的json结构不正确吗?
However, when the Post method receives this, all the Email fields are populated, except for the HandleBars dictionary. What do I have to do in order to pass it in correctly? Is my json structured incorrectly?
推荐答案
默认的JsonFormatter
无法从Javascript Array
绑定Dictionary
,因为它没有定义每个项目的键.
The default JsonFormatter
is unable to bind Dictionary
from Javascript Array
because it doesn't define a key to each item.
您需要改用Object
:
"HandleBars": {
"something": "value"
}
这篇关于WebAPI-使用JSON发布到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!