Asp.net Core 2 API POST Objects are NULL?

You need to include the [FromBody] attribute on the model:

[FromBody] MyTestModel model

See Andrew Lock's post for more information:

In order to bind the JSON correctly in ASP.NET Core, you must modify your action to include the attribute [FromBody] on the parameter. This tells the framework to use the content-type header of the request to decide which of the configured IInputFormatters to use for model binding.

As noted by @anserk in the comments, this also requires the Content-Type header to be set to application/json.


To add more information to the accepted answer:

There are three sources from which parameters are bound automatically without the use of an Attribute:

Form values: These are form values that go in the HTTP request using the POST method. (including jQuery POST requests).

Route values: The set of route values provided by Routing

Query strings: The query string part of the URI.

Note that Body is NOT one of them (though I think it should be).

So if you have values that need to be bound from the body, you MUST use the attribute binding attribute.

This tripped me up yesterday as I assumed that parameters from the Body would be bound automatically.

The second minor point is that only one parameter can be bound to the Body.

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.

Thus if there is more than one parameter you need, you need to create a Model class to bind them:

public class InputModel{
   public string FirstName{get;set;}
   public string LastName{get;set;}
}

[HttpPost]
public IActionResult test([FromBody]InputModel model)...

The Docs