ASP.NET Core – bind multiple controller parameters to body

Here are two things you need to know:

1.FromBody could not work with Get request.

2.Don’t apply [FromBody] to more than one parameter per action method. Once the request stream is read by an input formatter, it’s no longer available to be read again for binding other [FromBody] parameters.

For you do not want to pass the data by query and do not want to create dtos,I suggest that you could using Newtonsoft.Json.Linq.JObject:

public class GreetController : ControllerBase
{
    [HttpPost]
    public string Index([FromBody]JObject model)
    { 
        var firstname = model["firstname"].ToString();
        var lastname = model["lastname"].ToString();
        return $"Hello {firstname} {lastname}"; 
    }
}

Startup.cs:

services.AddControllers()
    .AddNewtonsoftJson();

For how to use Newtonsoft.Json in an ASP.NET Core 3.1 project:

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#use-newtonsoftjson-in-an-aspnet-core-30-mvc-project

Result: enter image description here

Another way is to custom model binder,you could follow the answer below:

https://stackoverflow.com/a/60611928/11398810

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top