.NET Core Web API: multiple [FromBody]?
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.
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
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 isnull
.[HttpPost] public class Search([FromBody]List<int> ids,[FromBody]SearchEntity searchEntity) { //ASP.NET Core MVC }
When I place the
ids
parameter in theSearchEntity
class, there is no problem. But I have lots of methods that are written like this. What can I do about this problem? -
BVernon almost 4 yearsBefore core, I was able to create a custom class to handle multiple parameters by caching the relevant part of the request stream. But with core the analogous code won't fire without
[FromBody]
so this solution no longer works. So annoying.