Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Web API: multiple [FromBody]?

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?

like image 211
Burak çağlayan Avatar asked May 27 '18 13:05

Burak çağlayan


2 Answers

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.

like image 199
Nkosi Avatar answered Sep 20 '22 20:09

Nkosi


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                                                                   
}
like image 44
Phil Prett Avatar answered Sep 18 '22 20:09

Phil Prett