Web Api-以复杂类型为参数的IEnumerable为null
本文关键字:参数 IEnumerable null 类型 Api- 复杂 Web | 更新日期: 2023-09-27 18:24:05
我有一个web api方法,看起来像这样:
[HttpPost]
[Route("message")]
public IHttpActionResult Post(IEnumerable<Email> email)
{
return Ok("message sent");
}
使用Fiddler,我发送了一个看起来像这样的请求:
User-Agent: Fiddler
Host: localhost:3994
Content-Length: 205
Content-Type: application/json; charset=utf-8
{
"To": "someone@emailaddress.com",
"From": "Tom",
"Body": "Cruise",
"Template":"template"
}
我的电子邮件类如下:
public class Email
{
public string Body { get; set; }
public string From { get; set; }
public string To { get; set; }
public string Template { get; set; }
它正在命中我的API方法,但返回null。我一直在谷歌上搜索并尝试json请求的所有不同变体,比如:
{
"email":
{
"To": "someone@emailaddress",
"From": "Tom",
"Body": "Cruise",
"Template": "template"
}
}
以及许多其他方式,但每次电子邮件参数都为null。我做错了什么?
如果您只想向一封邮件发送您的主机方法param和json数据是错误的
后方法
[HttpPost]
[Route("message")]
public IHttpActionResult Post(Email email)
{
return Ok("message sent");
}
Json Data
{
"Body":"body",
"From":"from",
"To":"to",
"Template":"template"
}
或者,如果你想发送更多的电子邮件,只有你的json数据是错误的
Json数据用于更多电子邮件
[
{"Body":"body","From":"from","To":"to","Template":"template"},
{"Body":"body1","From":"from1","To":"to1","Template":"template1"},
{"Body":"body2","From":"from2","To":"to2","Template":"template2"}
]
根据您的请求,看起来您只发布了一个Email
对象,因此将您的方法更改为:
[HttpPost]
[Route("message")]
public IHttpActionResult Post(Email email)
{
return Ok("message sent");
}
此外,您可能需要将您正在张贴的电子邮件包装为:
User-Agent: Fiddler
Host: localhost:3994
Content-Length: 205
Content-Type: application/json; charset=utf-8
{
"email":{
"To":"someone@emailaddress.com",
"From":"Tom",
"Body":"Cruise",
"Template":"template"
}
}