'Read action parameters from JSON properties

How can I get the parameters of an ASP.NET Core MVC controller action from the properties of a JSON object that was sent in the HTTP request body?

If the request body contains form data and the content type is appropriate, the action method parameters are populated automatically as expected.

But nothing works if the POST data format is JSON and the content type is "application/json". I think this is quite common for API requests? I tried adding the [FromBody] attribute to all parameters, but the documentation says I can only apply that once. Well, I can write it multiple times and nobody complains, but neither helps. Even if I want to bind all the JSON to a single string parameter, it remains null.

Can ASP.NET Core actually handle JSON POST data? In the usual parameter binding comfort? Or are we down to the feature level of PHP (or below) when it comes to JSON requests? Should I not use such advanced technology and revert my client-side code to plain old HTTP form data instead?

I think I used this before and saw it working. But can't find out what the difference is here. Maybe it only works in controllers with the [ApiController] attribute? This case is a regular web page controller, not a separate API. But it needs to provide functions to JavaScript as well, so it does both.



Solution 1:[1]

I tried adding the [FromBody] attribute to all parameters

This sounds fishy to me. Are you trying to send your params as a json object and expecting them to get unwrapped into individual action params?

Consider the following data type and MVC controller endpoint:

public class Sample
{
    public int Id { get; set; }
    public string Name { get; set; }
}

[HttpPost]
public IActionResult Post([FromBody] Sample sample) 
    => new JsonResult(sample);

This is all you need for a typical POST to an MVC controller. The key point is probably the type that I'm using to bind to the body. As you can see, I create a matching json object in Postman and it binds correctly and returns what I sent.

enter image description here

To get what you want, I think you'd have to rely on query params. (or some other technique I'm unaware of) Here's an example if you need it.

[HttpPost]
public IActionResult PostQuery([FromQuery] int id, [FromQuery] string name)
    => new JsonResult(new Sample {Id = id, Name = name});

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1