Core WebApi取不到List参数
坑点
Core WebApi参数List<T>无法取到。[1]
- 参数为T时可以正常获取
- 参数为List<T>时取不到
- 以上问题在Framework WebApi里面不会出现
参数T示例
[HttpPost("Insert")]
public IActionResult Insert(Student student)
{
return Ok(student);
}
这种情况是可以正常取到student的。
参数List<T>示例
[HttpPost("Inserts")]
public IActionResult Inserts(List<Student> students)
{
return Ok(students);
}
这种情况是无法取到students的,但是我们可以使用以下方法获取(不建议这样做)。
[HttpPost("Inserts")]
public IActionResult Inserts(List<Student> students)
{
List<Student> retStudents;
using (var sr = new StreamReader(HttpContext.Request.Body))
{
retStudents = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Student>>(sr.ReadLine());
}
return Ok(students);
}
解决办法
乖乖给参数加上修饰FromBody ,统里如果是form提交的就用FromForm。
[HttpPost("Inserts")]
public IActionResult Inserts([FromBody]List<Student> students)
{
return Ok(students);
}
不管什么参数都要加上修饰,尽在掌控总好过依赖默认值。
附一张参数修饰表
修饰 | 说明 |
---|---|
[FromBody] | 请求正文 |
[FromForm] | 请求正文中的表单数据 |
[FromHeader] | 请求标头 |
[FromQuery] | 请求查询字符串参数 |
[FromRoute] | 当前请求中的路由数据 |
[FromServices] | 作为操作参数插入的请求服务 |
framework经验,WebApi对象参数无修饰时全部为FromBody,但core不适用。 ↩︎