WebAPI - send to dictionary using json

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 is as follows:

 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 send my Post method using a violinist, for example:

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

It works great. However, I want 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 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 email fields are populated, with the exception of the HandleBars dictionary. What do I need to do to pass it correctly? Is my json structured incorrectly?

+5
source share
2 answers

By default, JsonFormatter cannot associate a Dictionary with a Javascript Array because it does not define a key for each element.

Instead, you need to use Object :

 "HandleBars": { "something": "value" } 
+6
source

You must have

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

Source: https://habr.com/ru/post/1237196/


All Articles