Vinicius Quinafelex Alves

🌐Ler em português

[ASPNET] Why the action parameter is null

In some cases, the action parameter that should be hydrated with the data sent by the user is null. The main reasons are:

1. Object is being hydrated from the wrong place

It's more common for the server to trigger a HTTP 415 error, but on some old dotnet versions such error is not triggered and the parameter is simply null.

Use [FromForm] for <form>, Multipart Form and Form URL Encoded POSTs

Use [FromBody] for raw JSON POSTs

Use [FromRoute] to get data from the URL route

Use [FromQuery] to get data passed on the URL query (after the question mark "?" on the URL)

[HttpPost]
public IActionResult Example([FromForm]DataModel data)
{
    /* Implementation */
}

2. Data of one of the properties is null or has a format that's not understood by the deserializer

Non-nullable properties cannot be hydrated if the data is null or not properly formatted. For example, Guid variables by default has to have dashes "-" and DateTime is much more predictable using the ISO format.

{
    "ValidNumbers": [123, 123.45, "123", "123.45"],
    "ValidGuids": ["7e31022d-b955-4b74-bcaf-82660196480b"],
    "ValidDates": ["2022-01-01", "2022-01-01T12:00:00", "2022-01-01T12:00:00-03:00"]
}

Even nullable properties cannot be hydrated if the property is a primitive, and the JSON body contains an array or an object.

{
    "ObjectProperty:" {},
    "ArrayProperty": []
}

In case you have no control over the input format, this article explains how you can add change the serialization and deserialization formats on the ASPNET environment.