10

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; }

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"}
]

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"
 }]

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?

mihai
  • 2,746
  • 3
  • 35
  • 56
ygetarts
  • 923
  • 3
  • 14
  • 29
  • 1
    Wouldn't it be (inside the json array) `{"value":"something","key":"key1"}` ? (depending on how you are casing your json it might be Value en Key) – Igor Dec 01 '15 at 21:04
  • `HandleBars` is a `` and you're only passing one `string`, as well as you should be giving the content inside `HandleBars` names `key` and `value` – ragerory Dec 01 '15 at 21:05
  • see, here is already a response http://stackoverflow.com/questions/2494294/sending-a-json-array-to-be-received-as-a-dictionarystring-string – mihai Dec 01 '15 at 21:07

2 Answers2

11

The default JsonFormatter is unable to bind Dictionary from Javascript Array because it doesn't define a key to each item.

You need to use an Object instead:

"HandleBars": {
  "something": "value"
}
haim770
  • 48,394
  • 7
  • 105
  • 133
1

You should have

{
   "Body": "body",
   "From": "from",
   "To": "to",
   "Template": "template",
   "HandleBars": [
        { key: 'key1', value: 'something'}
    ]
}
mihai
  • 2,746
  • 3
  • 35
  • 56