2015-12-01 74 views
5

到字典中我有一個Web API方法,看起來像這樣:的WebAPI - 發佈使用JSON

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

而且我張貼到我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結構是否不正確?

+1

豈不是(JSON數組內)'{ 「值」: 「東西」,」鍵「:」key1「}'? (具體取決於你如何封裝你的json,它可能是Value的關鍵) – Igor

+0

'HandleBars'是一個'''',你只傳遞一個'string',以及你應該給內部內容'HandleBars'名稱'鍵'和'值' – ragerory

+0

看到,這裏已經是一個迴應http://stackoverflow.com/questions/2494294/sending-a-json-array-to-be-received-as-a-dictionarystring -string – meorfi

回答

6

默認JsonFormatter無法綁定來自Javascript ArrayDictionary,因爲它沒有爲每個項目定義一個鍵。

你需要使用一個Object代替:

"HandleBars": { 
    "something": "value" 
} 
+0

這樣做了。謝謝。 – ygetarts

0

你應該有

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