Note on fixing the problem where ASP.NET Core 2 API controller always reports NULL during POST requests
Posted: (EET/GMT+2)
A quick note on creating Web API controllers with ASP.NET Core 2: if you want to make sure your input data is automatically bound to correct HTTP POST body values, you must explicitly set the [FromBody] attribute for your input model object.
For example, if you had code like this:
public class MyApiController : Controller
{
[HttpPost("api/somecontroller/somemethod")]
public async Task PostSomeData(MyInputDataModel entry)
{
try
{
if (entry == null)
{
throw new ArgumentNullException(nameof(entry));
}
...
…then you would notice that the "entry" parameter is never NULL, but all the properties inside it will be. In ASP.NET Core 2.0, the fix is simple, add the [FromBody] attribute before the input model object, like this:
public async TaskPostSomeData([FromBody] MyInputDataModel entry)
If you have already upgraded to ASP.NET Core 2.1, then you have a new attribute called ApiController at your disposal. If you decorate your API controller with this attribute, you don't need to explicitly set the [FromBody] attribute.
Hope this helps!