我有一个接受JObject的Web API2帖子操作。
[Route("api/Sendemail")]
public void Post([FromBody]JObject value)
{
var personalisation = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(value.First.ToString());
var recipientEmail = JsonConvert.DeserializeObject<string>(value.GetValue("Email").ToString());
var templateId = JsonConvert.DeserializeObject<string>(value.GetValue("TemplateId").ToString());
var response = _client.SendEmail(recipientEmail, templateId, personalisation);
}
我从我的控制器传入此内容:
[HttpPost]
public async Task<IActionResult> Index(FeedbackForm model)
{
//Send feedback to address
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var personalisation = new Dictionary<string, dynamic>
{
{"feedback",model.Feedback},
{"name",model.Name},
{"email",model.Email},
{"response",""},
{"referrer",model.Referrer}
};
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("Personalisation", personalisation.ToString()),
new KeyValuePair<string, string>("Email", "someone@example.com"),
new KeyValuePair<string, string>("TemplateId", "blah")
});
//Sending POST
var response = await client.PostAsync("http://localhost/api/sendemail", formContent);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return RedirectToAction("Thanks");
}
请求看起来正确,但我似乎无法正确反序列化,特别是Dictionary对象。正在正确检索Email和TemplateId。
我想我可能必须为帖子请求设一个强类型对象?