.NET Core Web API: multiple [FromBody]?

时光毁灭记忆、已成空白 提交于 2020-05-29 07:43:30

问题


I am converting code that was written in ASP.NET MVC to ASP.NET Core MVC. While I was converting the code, I encountered a problem. We used a method that has multiple parameters like this:

[HttpPost]                                                      
public class Search(List<int> ids, SearchEntity searchEntity)           
{   
  //ASP.NET MVC                                                                   
}

But when coding this in .NET Core, the ids parameter is null.

[HttpPost]                                                      
public class Search([FromBody]List<int> ids,[FromBody]SearchEntity searchEntity)           
{   
  //ASP.NET Core MVC                                                                   
} 

When I place the ids parameter in the SearchEntity class, there is no problem. But I have lots of methods that are written like this. What can I do about this problem?


回答1:


Can only have one FromBody as the body can only be read once

Reference Model Binding in ASP.NET Core

There can be at most one parameter per action decorated with [FromBody]. The ASP.NET Core MVC run-time delegates the responsibility of reading the request stream to the formatter. Once the request stream is read for a parameter, it's generally not possible to read the request stream again for binding other [FromBody] parameters.

MVC Core is stricter on how to bind model to actions. You also have to explicitly indicate where you want to bind the data from when you want to customize binding behavior.



来源:https://stackoverflow.com/questions/50552702/net-core-web-api-multiple-frombody

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!