我很难弄清楚为什么我的JSON没有在MVC控制器中正确反序列化。控制器操作在这里:
[HttpPost]
public IActionResult Post(MessageRequest messageRequest)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Task.Run(() => _emailService.SendMessageAsync(messageRequest));
return Ok();
}
MessageRequest模型及其成员的定义如下:
public class MessageRequest
{
[Required(ErrorMessage = "A message is required.")]
[DataMember(Name="message")]
public MessagePayload Payload { get; set; }
[DataMember(Name="origin")]
[Required(ErrorMessage = "An origin is required for every message.")]
public Origin Origin { get; set; }
}
public class MessagePayload
{
[DataMember(Name = "from")]
public EmailAddress From { get; set; }
[DataMember(Name = "to")]
public IEnumerable<EmailAddress> To { get; set; }
[DataMember(Name = "cc")]
public IEnumerable<EmailAddress> Cc { get; set; }
[DataMember(Name = "bcc")]
public IEnumerable<EmailAddress> Bcc { get; set; }
[DataMember(Name = "subject")]
public string Subject { get; set; }
[DataMember(Name = "content")]
public Content Content { get; set; }
}
public class Origin
{
[Required]
[DataMember(Name = "origin_url")]
public string Url { get; set; }
[Required]
[DataMember(Name = "origin_message_id")]
public string MessageId { get; set; }
}
我无法弄清楚为什么下面的JSON帖子请求没有正确反序列化。
{
"message":{
"from":"gumby@jacketforce.ca",
"to":[
{
"name":"Bubba Gump",
"email":"bubba.gump.dm@gmail.com"
}
],
"subject":"A new mail for mr bubbles",
"content":{
"html":"<html><h1>This is definitely html</h1></html>",
"text":"This is a text email instead"
}
},
"origin":{
"origin_url":"http://requestb.in/bin",
"origin_message_id":"MESSAGE_ID_DOESNT_MATTER"
}
}
我尝试添加和删除 DataContract 和 DataMember 属性, FromBody 属性,删除序列化属性并更改属性的名称他们在JSON中的名字。一天早上,我开始工作,几乎神奇地,一切都在改变之后工作(无论如何都没有明显的)。据我所知,我发送的JSON完全根据提供的型号规格形成。有时我得到一个完全为空的动作参数,而有时候我会得到一个非null参数,它的所有属性都是null。
为什么我无法将JSON可靠地反序列化为我的某个对象类型?