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?
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.
I have used a solution where multiple parameters are sent as [FromBody] using a tuple:
[HttpPost]
public class Search([FromBody](List<int> ids, SearchEntity searchEntity) parameters)
{
//ASP.NET Core MVC
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With